Merge "Load splits on-demand"
diff --git a/Android.mk b/Android.mk
index b98d3bc..e372fda 100644
--- a/Android.mk
+++ b/Android.mk
@@ -213,7 +213,6 @@
 	core/java/android/hardware/usb/IUsbManager.aidl \
 	core/java/android/net/ICaptivePortal.aidl \
 	core/java/android/net/IConnectivityManager.aidl \
-	core/java/android/net/IConnectivityMetricsLogger.aidl \
 	core/java/android/net/IIpConnectivityMetrics.aidl \
 	core/java/android/net/IEthernetManager.aidl \
 	core/java/android/net/IEthernetServiceListener.aidl \
diff --git a/api/current.txt b/api/current.txt
index 202ea21..4270b4f 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -4737,6 +4737,7 @@
     method public abstract android.app.Fragment getPrimaryNavigationFragment();
     method public void invalidateOptionsMenu();
     method public abstract boolean isDestroyed();
+    method public abstract boolean isStateSaved();
     method public abstract void popBackStack();
     method public abstract void popBackStack(java.lang.String, int);
     method public abstract void popBackStack(int, int);
@@ -6547,6 +6548,7 @@
   public static class AssistStructure.ViewNode {
     method public float getAlpha();
     method public android.view.autofill.AutoFillId getAutoFillId();
+    method public java.lang.String[] getAutoFillOptions();
     method public android.view.autofill.AutoFillType getAutoFillType();
     method public android.view.autofill.AutoFillValue getAutoFillValue();
     method public android.app.assist.AssistStructure.ViewNode getChildAt(int);
@@ -6882,6 +6884,7 @@
     method public long getFreeBytes(java.lang.String);
     method public long getTotalBytes(java.lang.String);
     method public android.app.usage.ExternalStorageStats queryExternalStatsForUser(java.lang.String, android.os.UserHandle);
+    method public android.app.usage.StorageStats queryStatsForPackage(java.lang.String, java.lang.String, android.os.UserHandle);
     method public android.app.usage.StorageStats queryStatsForUid(java.lang.String, int);
     method public android.app.usage.StorageStats queryStatsForUser(java.lang.String, android.os.UserHandle);
   }
@@ -20797,6 +20800,7 @@
     field public static final int AUDIOFOCUS_LOSS = -1; // 0xffffffff
     field public static final int AUDIOFOCUS_LOSS_TRANSIENT = -2; // 0xfffffffe
     field public static final int AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK = -3; // 0xfffffffd
+    field public static final int AUDIOFOCUS_NONE = 0; // 0x0
     field public static final int AUDIOFOCUS_REQUEST_FAILED = 0; // 0x0
     field public static final int AUDIOFOCUS_REQUEST_GRANTED = 1; // 0x1
     field public static final int AUDIO_SESSION_ID_GENERATE = 0; // 0x0
@@ -40152,7 +40156,7 @@
 
 package android.test.suitebuilder {
 
-  public class TestMethod {
+  public deprecated class TestMethod {
     ctor public TestMethod(java.lang.reflect.Method, java.lang.Class<? extends junit.framework.TestCase>);
     ctor public TestMethod(java.lang.String, java.lang.Class<? extends junit.framework.TestCase>);
     ctor public TestMethod(junit.framework.TestCase);
@@ -40163,7 +40167,7 @@
     method public java.lang.String getName();
   }
 
-  public class TestSuiteBuilder {
+  public deprecated class TestSuiteBuilder {
     ctor public TestSuiteBuilder(java.lang.Class);
     ctor public TestSuiteBuilder(java.lang.String, java.lang.ClassLoader);
     method public android.test.suitebuilder.TestSuiteBuilder addRequirements(java.util.List<com.android.internal.util.Predicate<android.test.suitebuilder.TestMethod>>);
@@ -40176,7 +40180,7 @@
     method public android.test.suitebuilder.TestSuiteBuilder named(java.lang.String);
   }
 
-  public static class TestSuiteBuilder.FailedToCreateTests extends junit.framework.TestCase {
+  public static deprecated class TestSuiteBuilder.FailedToCreateTests extends junit.framework.TestCase {
     ctor public TestSuiteBuilder.FailedToCreateTests(java.lang.Exception);
     method public void testSuiteConstructionFailed();
   }
@@ -43139,11 +43143,13 @@
     field public static final int DRAW_DURATION = 4; // 0x4
     field public static final int FIRST_DRAW_FRAME = 9; // 0x9
     field public static final int INPUT_HANDLING_DURATION = 1; // 0x1
+    field public static final int INTENDED_VSYNC_TIMESTAMP = 10; // 0xa
     field public static final int LAYOUT_MEASURE_DURATION = 3; // 0x3
     field public static final int SWAP_BUFFERS_DURATION = 7; // 0x7
     field public static final int SYNC_DURATION = 5; // 0x5
     field public static final int TOTAL_DURATION = 8; // 0x8
     field public static final int UNKNOWN_DELAY_DURATION = 0; // 0x0
+    field public static final int VSYNC_TIMESTAMP = 11; // 0xb
   }
 
   public abstract class FrameStats {
@@ -45642,6 +45648,7 @@
     method public abstract void setAccessibilityFocused(boolean);
     method public abstract void setActivated(boolean);
     method public abstract void setAlpha(float);
+    method public abstract void setAutoFillOptions(java.lang.String[]);
     method public abstract void setAutoFillType(android.view.autofill.AutoFillType);
     method public abstract void setAutoFillValue(android.view.autofill.AutoFillValue);
     method public abstract void setCheckable(boolean);
@@ -50824,6 +50831,8 @@
     method public int resolveAdjustedSize(int, int);
     method public void resume();
     method public void seekTo(int);
+    method public void setAudioAttributes(android.media.AudioAttributes);
+    method public void setAudioFocusRequest(int);
     method public void setMediaController(android.widget.MediaController);
     method public void setOnCompletionListener(android.media.MediaPlayer.OnCompletionListener);
     method public void setOnErrorListener(android.media.MediaPlayer.OnErrorListener);
@@ -50928,7 +50937,7 @@
 
 package com.android.internal.util {
 
-  public abstract interface Predicate<T> {
+  public abstract deprecated interface Predicate<T> {
     method public abstract boolean apply(T);
   }
 
diff --git a/api/system-current.txt b/api/system-current.txt
index 2f67204..75095b3 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -4898,6 +4898,7 @@
     method public abstract android.app.Fragment getPrimaryNavigationFragment();
     method public void invalidateOptionsMenu();
     method public abstract boolean isDestroyed();
+    method public abstract boolean isStateSaved();
     method public abstract void popBackStack();
     method public abstract void popBackStack(java.lang.String, int);
     method public abstract void popBackStack(int, int);
@@ -6787,6 +6788,7 @@
   public static class AssistStructure.ViewNode {
     method public float getAlpha();
     method public android.view.autofill.AutoFillId getAutoFillId();
+    method public java.lang.String[] getAutoFillOptions();
     method public android.view.autofill.AutoFillType getAutoFillType();
     method public android.view.autofill.AutoFillValue getAutoFillValue();
     method public android.app.assist.AssistStructure.ViewNode getChildAt(int);
@@ -7304,6 +7306,7 @@
     method public long getFreeBytes(java.lang.String);
     method public long getTotalBytes(java.lang.String);
     method public android.app.usage.ExternalStorageStats queryExternalStatsForUser(java.lang.String, android.os.UserHandle);
+    method public android.app.usage.StorageStats queryStatsForPackage(java.lang.String, java.lang.String, android.os.UserHandle);
     method public android.app.usage.StorageStats queryStatsForUid(java.lang.String, int);
     method public android.app.usage.StorageStats queryStatsForUser(java.lang.String, android.os.UserHandle);
   }
@@ -22464,6 +22467,7 @@
     field public static final int AUDIOFOCUS_LOSS = -1; // 0xffffffff
     field public static final int AUDIOFOCUS_LOSS_TRANSIENT = -2; // 0xfffffffe
     field public static final int AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK = -3; // 0xfffffffd
+    field public static final int AUDIOFOCUS_NONE = 0; // 0x0
     field public static final int AUDIOFOCUS_REQUEST_FAILED = 0; // 0x0
     field public static final int AUDIOFOCUS_REQUEST_GRANTED = 1; // 0x1
     field public static final int AUDIO_SESSION_ID_GENERATE = 0; // 0x0
@@ -26828,44 +26832,6 @@
     method public void onTetheringStarted();
   }
 
-  public final class ConnectivityMetricsEvent implements android.os.Parcelable {
-    ctor public ConnectivityMetricsEvent(long, int, int, android.os.Parcelable);
-    method public int describeContents();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.ConnectivityMetricsEvent> CREATOR;
-    field public final int componentTag;
-    field public final android.os.Parcelable data;
-    field public final int eventTag;
-    field public final long timestamp;
-  }
-
-  public static final class ConnectivityMetricsEvent.Reference implements android.os.Parcelable {
-    ctor public ConnectivityMetricsEvent.Reference(long);
-    method public int describeContents();
-    method public long getValue();
-    method public void readFromParcel(android.os.Parcel);
-    method public void setValue(long);
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.ConnectivityMetricsEvent.Reference> CREATOR;
-  }
-
-  public class ConnectivityMetricsLogger {
-    ctor public ConnectivityMetricsLogger();
-    method public android.net.ConnectivityMetricsEvent[] getEvents(android.net.ConnectivityMetricsEvent.Reference);
-    method public void logEvent(long, int, int, android.os.Parcelable);
-    method public boolean register(android.app.PendingIntent);
-    method public boolean unregister(android.app.PendingIntent);
-    field public static final int COMPONENT_TAG_BLUETOOTH = 1; // 0x1
-    field public static final int COMPONENT_TAG_CONNECTIVITY = 0; // 0x0
-    field public static final int COMPONENT_TAG_TELECOM = 3; // 0x3
-    field public static final int COMPONENT_TAG_TELEPHONY = 4; // 0x4
-    field public static final int COMPONENT_TAG_WIFI = 2; // 0x2
-    field public static final java.lang.String CONNECTIVITY_METRICS_LOGGER_SERVICE = "connectivity_metrics_logger";
-    field public static final java.lang.String DATA_KEY_EVENTS_COUNT = "count";
-    field public static final int NUMBER_OF_COMPONENTS = 5; // 0x5
-    field public static final int TAG_SKIPPED_EVENTS = -1; // 0xffffffff
-  }
-
   public class Credentials {
     ctor public Credentials(int, int, int);
     method public int getGid();
@@ -27577,175 +27543,6 @@
 
 }
 
-package android.net.metrics {
-
-  public final class ApfProgramEvent implements android.os.Parcelable {
-    method public int describeContents();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.metrics.ApfProgramEvent> CREATOR;
-    field public static final int FLAG_HAS_IPV4_ADDRESS = 1; // 0x1
-    field public static final int FLAG_MULTICAST_FILTER_ON = 0; // 0x0
-    field public final int currentRas;
-    field public final int filteredRas;
-    field public final int flags;
-    field public final long lifetime;
-    field public final int programLength;
-  }
-
-  public final class ApfStats implements android.os.Parcelable {
-    method public int describeContents();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.metrics.ApfStats> CREATOR;
-    field public final int droppedRas;
-    field public final long durationMs;
-    field public final int matchingRas;
-    field public final int maxProgramSize;
-    field public final int parseErrors;
-    field public final int programUpdates;
-    field public final int receivedRas;
-    field public final int zeroLifetimeRas;
-  }
-
-  public final class DefaultNetworkEvent implements android.os.Parcelable {
-    method public int describeContents();
-    method public static void logEvent(int, int[], int, boolean, boolean);
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.metrics.DefaultNetworkEvent> CREATOR;
-    field public final int netId;
-    field public final boolean prevIPv4;
-    field public final boolean prevIPv6;
-    field public final int prevNetId;
-    field public final int[] transportTypes;
-  }
-
-  public final class DhcpClientEvent implements android.os.Parcelable {
-    method public int describeContents();
-    method public static void logStateEvent(java.lang.String, java.lang.String);
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.metrics.DhcpClientEvent> CREATOR;
-    field public final int durationMs;
-    field public final java.lang.String ifName;
-    field public final java.lang.String msg;
-  }
-
-  public final class DhcpErrorEvent implements android.os.Parcelable {
-    method public int describeContents();
-    method public static int errorCodeWithOption(int, int);
-    method public static void logParseError(java.lang.String, int);
-    method public static void logReceiveError(java.lang.String);
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final int BOOTP_TOO_SHORT;
-    field public static final int BUFFER_UNDERFLOW;
-    field public static final android.os.Parcelable.Creator<android.net.metrics.DhcpErrorEvent> CREATOR;
-    field public static final int DHCP_BAD_MAGIC_COOKIE;
-    field public static final int DHCP_ERROR = 4; // 0x4
-    field public static final int DHCP_INVALID_OPTION_LENGTH;
-    field public static final int DHCP_NO_MSG_TYPE;
-    field public static final int DHCP_UNKNOWN_MSG_TYPE;
-    field public static final int L2_ERROR = 1; // 0x1
-    field public static final int L2_TOO_SHORT;
-    field public static final int L2_WRONG_ETH_TYPE;
-    field public static final int L3_ERROR = 2; // 0x2
-    field public static final int L3_INVALID_IP;
-    field public static final int L3_NOT_IPV4;
-    field public static final int L3_TOO_SHORT;
-    field public static final int L4_ERROR = 3; // 0x3
-    field public static final int L4_NOT_UDP;
-    field public static final int L4_WRONG_PORT;
-    field public static final int MISC_ERROR = 5; // 0x5
-    field public static final int RECEIVE_ERROR;
-    field public final int errorCode;
-    field public final java.lang.String ifName;
-  }
-
-  public final class DnsEvent implements android.os.Parcelable {
-    method public int describeContents();
-    method public static void logEvent(int, byte[], byte[], int[]);
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.metrics.DnsEvent> CREATOR;
-    field public final byte[] eventTypes;
-    field public final int[] latenciesMs;
-    field public final int netId;
-    field public final byte[] returnCodes;
-  }
-
-  public final class IpManagerEvent implements android.os.Parcelable {
-    method public int describeContents();
-    method public static void logEvent(int, java.lang.String, long);
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final int COMPLETE_LIFECYCLE = 3; // 0x3
-    field public static final android.os.Parcelable.Creator<android.net.metrics.IpManagerEvent> CREATOR;
-    field public static final int PROVISIONING_FAIL = 2; // 0x2
-    field public static final int PROVISIONING_OK = 1; // 0x1
-    field public final long durationMs;
-    field public final int eventType;
-    field public final java.lang.String ifName;
-  }
-
-  public final class IpReachabilityEvent implements android.os.Parcelable {
-    method public int describeContents();
-    method public static void logNudFailed(java.lang.String);
-    method public static void logProbeEvent(java.lang.String, int);
-    method public static void logProvisioningLost(java.lang.String);
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.metrics.IpReachabilityEvent> CREATOR;
-    field public static final int NUD_FAILED = 512; // 0x200
-    field public static final int PROBE = 256; // 0x100
-    field public static final int PROVISIONING_LOST = 768; // 0x300
-    field public final int eventType;
-    field public final java.lang.String ifName;
-  }
-
-  public final class NetworkEvent implements android.os.Parcelable {
-    method public int describeContents();
-    method public static void logCaptivePortalFound(int, long);
-    method public static void logEvent(int, int);
-    method public static void logValidated(int, long);
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.metrics.NetworkEvent> CREATOR;
-    field public static final int NETWORK_CAPTIVE_PORTAL_FOUND = 4; // 0x4
-    field public static final int NETWORK_CONNECTED = 1; // 0x1
-    field public static final int NETWORK_DISCONNECTED = 7; // 0x7
-    field public static final int NETWORK_LINGER = 5; // 0x5
-    field public static final int NETWORK_UNLINGER = 6; // 0x6
-    field public static final int NETWORK_VALIDATED = 2; // 0x2
-    field public static final int NETWORK_VALIDATION_FAILED = 3; // 0x3
-    field public final long durationMs;
-    field public final int eventType;
-    field public final int netId;
-  }
-
-  public final class RaEvent implements android.os.Parcelable {
-    method public int describeContents();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.metrics.RaEvent> CREATOR;
-    field public final long dnsslLifetime;
-    field public final long prefixPreferredLifetime;
-    field public final long prefixValidLifetime;
-    field public final long rdnssLifetime;
-    field public final long routeInfoLifetime;
-    field public final long routerLifetime;
-  }
-
-  public final class ValidationProbeEvent implements android.os.Parcelable {
-    method public int describeContents();
-    method public static void logEvent(int, long, int, int);
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.net.metrics.ValidationProbeEvent> CREATOR;
-    field public static final int DNS_FAILURE = 0; // 0x0
-    field public static final int DNS_SUCCESS = 1; // 0x1
-    field public static final int PROBE_DNS = 0; // 0x0
-    field public static final int PROBE_HTTP = 1; // 0x1
-    field public static final int PROBE_HTTPS = 2; // 0x2
-    field public static final int PROBE_PAC = 3; // 0x3
-    field public final long durationMs;
-    field public final int netId;
-    field public final int probeType;
-    field public final int returnCode;
-  }
-
-}
-
 package android.net.nsd {
 
   public final class NsdManager {
@@ -43696,7 +43493,7 @@
 
 package android.test.suitebuilder {
 
-  public class TestMethod {
+  public deprecated class TestMethod {
     ctor public TestMethod(java.lang.reflect.Method, java.lang.Class<? extends junit.framework.TestCase>);
     ctor public TestMethod(java.lang.String, java.lang.Class<? extends junit.framework.TestCase>);
     ctor public TestMethod(junit.framework.TestCase);
@@ -43707,7 +43504,7 @@
     method public java.lang.String getName();
   }
 
-  public class TestSuiteBuilder {
+  public deprecated class TestSuiteBuilder {
     ctor public TestSuiteBuilder(java.lang.Class);
     ctor public TestSuiteBuilder(java.lang.String, java.lang.ClassLoader);
     method public android.test.suitebuilder.TestSuiteBuilder addRequirements(java.util.List<com.android.internal.util.Predicate<android.test.suitebuilder.TestMethod>>);
@@ -43720,7 +43517,7 @@
     method public android.test.suitebuilder.TestSuiteBuilder named(java.lang.String);
   }
 
-  public static class TestSuiteBuilder.FailedToCreateTests extends junit.framework.TestCase {
+  public static deprecated class TestSuiteBuilder.FailedToCreateTests extends junit.framework.TestCase {
     ctor public TestSuiteBuilder.FailedToCreateTests(java.lang.Exception);
     method public void testSuiteConstructionFailed();
   }
@@ -46684,11 +46481,13 @@
     field public static final int DRAW_DURATION = 4; // 0x4
     field public static final int FIRST_DRAW_FRAME = 9; // 0x9
     field public static final int INPUT_HANDLING_DURATION = 1; // 0x1
+    field public static final int INTENDED_VSYNC_TIMESTAMP = 10; // 0xa
     field public static final int LAYOUT_MEASURE_DURATION = 3; // 0x3
     field public static final int SWAP_BUFFERS_DURATION = 7; // 0x7
     field public static final int SYNC_DURATION = 5; // 0x5
     field public static final int TOTAL_DURATION = 8; // 0x8
     field public static final int UNKNOWN_DELAY_DURATION = 0; // 0x0
+    field public static final int VSYNC_TIMESTAMP = 11; // 0xb
   }
 
   public abstract class FrameStats {
@@ -49187,6 +48986,7 @@
     method public abstract void setAccessibilityFocused(boolean);
     method public abstract void setActivated(boolean);
     method public abstract void setAlpha(float);
+    method public abstract void setAutoFillOptions(java.lang.String[]);
     method public abstract void setAutoFillType(android.view.autofill.AutoFillType);
     method public abstract void setAutoFillValue(android.view.autofill.AutoFillValue);
     method public abstract void setCheckable(boolean);
@@ -54733,6 +54533,8 @@
     method public int resolveAdjustedSize(int, int);
     method public void resume();
     method public void seekTo(int);
+    method public void setAudioAttributes(android.media.AudioAttributes);
+    method public void setAudioFocusRequest(int);
     method public void setMediaController(android.widget.MediaController);
     method public void setOnCompletionListener(android.media.MediaPlayer.OnCompletionListener);
     method public void setOnErrorListener(android.media.MediaPlayer.OnErrorListener);
@@ -54837,7 +54639,7 @@
 
 package com.android.internal.util {
 
-  public abstract interface Predicate<T> {
+  public abstract deprecated interface Predicate<T> {
     method public abstract boolean apply(T);
   }
 
diff --git a/api/test-current.txt b/api/test-current.txt
index 41f279b..af8bb7f 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -4747,6 +4747,7 @@
     method public abstract android.app.Fragment getPrimaryNavigationFragment();
     method public void invalidateOptionsMenu();
     method public abstract boolean isDestroyed();
+    method public abstract boolean isStateSaved();
     method public abstract void popBackStack();
     method public abstract void popBackStack(java.lang.String, int);
     method public abstract void popBackStack(int, int);
@@ -6573,6 +6574,7 @@
   public static class AssistStructure.ViewNode {
     method public float getAlpha();
     method public android.view.autofill.AutoFillId getAutoFillId();
+    method public java.lang.String[] getAutoFillOptions();
     method public android.view.autofill.AutoFillType getAutoFillType();
     method public android.view.autofill.AutoFillValue getAutoFillValue();
     method public android.app.assist.AssistStructure.ViewNode getChildAt(int);
@@ -6908,6 +6910,7 @@
     method public long getFreeBytes(java.lang.String);
     method public long getTotalBytes(java.lang.String);
     method public android.app.usage.ExternalStorageStats queryExternalStatsForUser(java.lang.String, android.os.UserHandle);
+    method public android.app.usage.StorageStats queryStatsForPackage(java.lang.String, java.lang.String, android.os.UserHandle);
     method public android.app.usage.StorageStats queryStatsForUid(java.lang.String, int);
     method public android.app.usage.StorageStats queryStatsForUser(java.lang.String, android.os.UserHandle);
   }
@@ -20893,6 +20896,7 @@
     field public static final int AUDIOFOCUS_LOSS = -1; // 0xffffffff
     field public static final int AUDIOFOCUS_LOSS_TRANSIENT = -2; // 0xfffffffe
     field public static final int AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK = -3; // 0xfffffffd
+    field public static final int AUDIOFOCUS_NONE = 0; // 0x0
     field public static final int AUDIOFOCUS_REQUEST_FAILED = 0; // 0x0
     field public static final int AUDIOFOCUS_REQUEST_GRANTED = 1; // 0x1
     field public static final int AUDIO_SESSION_ID_GENERATE = 0; // 0x0
@@ -40340,7 +40344,7 @@
 
 package android.test.suitebuilder {
 
-  public class TestMethod {
+  public deprecated class TestMethod {
     ctor public TestMethod(java.lang.reflect.Method, java.lang.Class<? extends junit.framework.TestCase>);
     ctor public TestMethod(java.lang.String, java.lang.Class<? extends junit.framework.TestCase>);
     ctor public TestMethod(junit.framework.TestCase);
@@ -40351,7 +40355,7 @@
     method public java.lang.String getName();
   }
 
-  public class TestSuiteBuilder {
+  public deprecated class TestSuiteBuilder {
     ctor public TestSuiteBuilder(java.lang.Class);
     ctor public TestSuiteBuilder(java.lang.String, java.lang.ClassLoader);
     method public android.test.suitebuilder.TestSuiteBuilder addRequirements(java.util.List<com.android.internal.util.Predicate<android.test.suitebuilder.TestMethod>>);
@@ -40364,7 +40368,7 @@
     method public android.test.suitebuilder.TestSuiteBuilder named(java.lang.String);
   }
 
-  public static class TestSuiteBuilder.FailedToCreateTests extends junit.framework.TestCase {
+  public static deprecated class TestSuiteBuilder.FailedToCreateTests extends junit.framework.TestCase {
     ctor public TestSuiteBuilder.FailedToCreateTests(java.lang.Exception);
     method public void testSuiteConstructionFailed();
   }
@@ -43492,11 +43496,13 @@
     field public static final int DRAW_DURATION = 4; // 0x4
     field public static final int FIRST_DRAW_FRAME = 9; // 0x9
     field public static final int INPUT_HANDLING_DURATION = 1; // 0x1
+    field public static final int INTENDED_VSYNC_TIMESTAMP = 10; // 0xa
     field public static final int LAYOUT_MEASURE_DURATION = 3; // 0x3
     field public static final int SWAP_BUFFERS_DURATION = 7; // 0x7
     field public static final int SYNC_DURATION = 5; // 0x5
     field public static final int TOTAL_DURATION = 8; // 0x8
     field public static final int UNKNOWN_DELAY_DURATION = 0; // 0x0
+    field public static final int VSYNC_TIMESTAMP = 11; // 0xb
   }
 
   public abstract class FrameStats {
@@ -46004,6 +46010,7 @@
     method public abstract void setAccessibilityFocused(boolean);
     method public abstract void setActivated(boolean);
     method public abstract void setAlpha(float);
+    method public abstract void setAutoFillOptions(java.lang.String[]);
     method public abstract void setAutoFillType(android.view.autofill.AutoFillType);
     method public abstract void setAutoFillValue(android.view.autofill.AutoFillValue);
     method public abstract void setCheckable(boolean);
@@ -51203,6 +51210,8 @@
     method public int resolveAdjustedSize(int, int);
     method public void resume();
     method public void seekTo(int);
+    method public void setAudioAttributes(android.media.AudioAttributes);
+    method public void setAudioFocusRequest(int);
     method public void setMediaController(android.widget.MediaController);
     method public void setOnCompletionListener(android.media.MediaPlayer.OnCompletionListener);
     method public void setOnErrorListener(android.media.MediaPlayer.OnErrorListener);
@@ -51307,7 +51316,7 @@
 
 package com.android.internal.util {
 
-  public abstract interface Predicate<T> {
+  public abstract deprecated interface Predicate<T> {
     method public abstract boolean apply(T);
   }
 
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index 6fc60e9..0193c5f 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -844,6 +844,8 @@
 
     private boolean mHasCurrentPermissionsRequest;
 
+    private boolean mAutoFillResetNeeded;
+
     private static native String getDlWarning();
 
     /** Return the intent that started this activity. */
@@ -1780,7 +1782,7 @@
         getApplication().dispatchActivityStopped(this);
         mTranslucentCallback = null;
         mCalled = true;
-        if (isFinishing() && AutoFillManager.isClientActive(getActivityToken())) {
+        if (isFinishing() && mAutoFillResetNeeded) {
             getSystemService(AutoFillManager.class).reset();
         }
     }
@@ -2820,7 +2822,9 @@
             return;
         }
 
-        if (!mFragments.getFragmentManager().popBackStackImmediate()) {
+        FragmentManager fragmentManager = mFragments.getFragmentManager();
+
+        if (fragmentManager.isStateSaved() || !fragmentManager.popBackStackImmediate()) {
             finishAfterTransition();
         }
     }
@@ -6746,8 +6750,6 @@
         mCurrentConfig = config;
 
         mWindow.setColorMode(info.colorMode);
-
-        AutoFillManager.addClient(token, this);
     }
 
     /** @hide */
@@ -7214,6 +7216,12 @@
         }
     }
 
+    /** @hide */
+    @Override
+    public void resetableStateAvailable() {
+        mAutoFillResetNeeded = true;
+    }
+
     class HostCallbacks extends FragmentHostCallback<Activity> {
         public HostCallbacks() {
             super(Activity.this /*activity*/);
diff --git a/core/java/android/app/ActivityManagerInternal.java b/core/java/android/app/ActivityManagerInternal.java
index 4e34552..fa64a0f 100644
--- a/core/java/android/app/ActivityManagerInternal.java
+++ b/core/java/android/app/ActivityManagerInternal.java
@@ -22,7 +22,6 @@
 import android.content.IIntentSender;
 import android.content.Intent;
 import android.content.res.Configuration;
-import android.net.NetworkPolicyManager.UidStateWithSeqObserver;
 import android.os.Bundle;
 import android.os.IBinder;
 import android.service.voice.IVoiceInteractionSession;
@@ -234,16 +233,4 @@
      * @see android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY
      */
     public abstract void setHasOverlayUi(int pid, boolean hasOverlayUi);
-
-    /**
-     * Set observer which listens to uid state changes. Uid state change along with the sequence
-     * number associated with it needs to be passed to {@link UidStateWithSeqObserver}.
-     */
-    public abstract void setUidStateWithSeqObserver(UidStateWithSeqObserver observer);
-
-    /**
-     * Notifies that NetworkPolicyManagerService has updated the network policy rules for
-     * a specific {@param uid} and {@param procStateSeq}.
-     */
-    public abstract void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq);
 }
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index be70dcd..ce9d91f 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -180,7 +180,6 @@
     public static final boolean DEBUG_CONFIGURATION = false;
     private static final boolean DEBUG_SERVICE = false;
     private static final boolean DEBUG_MEMORY_TRIM = false;
-    private static final boolean DEBUG_NETWORK = false;
     private static final boolean DEBUG_PROVIDER = false;
     private static final boolean DEBUG_ORDER = false;
     private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
@@ -203,55 +202,6 @@
     // Whether to invoke an activity callback after delivering new configuration.
     private static final boolean REPORT_TO_ACTIVITY = true;
 
-    /**
-     * This is the time main thread waits for the NetworkPolicyManagerService to notify
-     * that network is unrestricted. After this the app components will be launched anyway.
-     */
-    private long mWaitForNetworkTimeoutMs;
-
-    /**
-     * This is only for logging purposes. This will help us identify if the waiting for network
-     * is responsible for any lag that user might see.
-     */
-    private static final int WAIT_FOR_NETWORK_THRESHOLD_MS = 100; // 0.1 sec
-
-    /**
-     * State indicating that there is no need for any blocking for network.
-     */
-    public static final int NETWORK_STATE_NO_CHANGE = 0;
-
-    /**
-     * State indicating that main thread should wait for ActivityManagerService to notify
-     * before the app components are launched.
-     */
-    public static final int NETWORK_STATE_BLOCK = 1;
-
-    /**
-     * State indicating that any threads waiting for ActivityManagerService to notify should
-     * be unblocked.
-     */
-    public static final int NETWORK_STATE_UNBLOCK = 2;
-
-    /**
-     * Constant for indicating a invalid sequence number.
-     */
-    public static final long INVALID_PROC_STATE_SEQ = -1;
-
-    /**
-     * Current sequence number associated with the process state change.
-     */
-    @GuardedBy("mNetworkPolicyLock")
-    private long mCurProcStateSeq;
-
-    /**
-     * Indicates whether any component being launched should block for network before
-     * proceeding.
-     */
-    @GuardedBy("mNetworkPolicyLock")
-    private boolean mShouldBlockForNetwork;
-
-    private Object mNetworkPolicyLock = new Object();
-
     private ContextImpl mSystemContext;
 
     static volatile IPackageManager sPackageManager;
@@ -1363,18 +1313,6 @@
         }
 
         @Override
-        public void setBlockForNetworkState(int blockState, long targetProcStateSeq) {
-            synchronized (mNetworkPolicyLock) {
-                if (blockState == NETWORK_STATE_UNBLOCK) {
-                    unblockForNetworkAccessLN(targetProcStateSeq);
-                } else if (blockState == NETWORK_STATE_BLOCK) {
-                    mShouldBlockForNetwork = true;
-                }
-                mCurProcStateSeq = targetProcStateSeq;
-            }
-        }
-
-        @Override
         public void scheduleInstallProvider(ProviderInfo provider) {
             sendMessage(H.INSTALL_PROVIDER, provider);
         }
@@ -1457,13 +1395,6 @@
         public void handleTrustStorageUpdate() {
             NetworkSecurityPolicy.getInstance().handleTrustStorageUpdate();
         }
-
-        @Override
-        public void notifyNetworkStateUpdated(long curProcStateSeq) {
-            synchronized (mNetworkPolicyLock) {
-                unblockForNetworkAccessLN(curProcStateSeq);
-            }
-        }
     }
 
     private int getLifecycleSeq() {
@@ -2163,79 +2094,6 @@
         }
     }
 
-    void blockForNetworkAccessInForegroundService(long procStateSeq) {
-        synchronized (mNetworkPolicyLock) {
-            if (mCurProcStateSeq >= procStateSeq) {
-                if (mShouldBlockForNetwork) {
-                    blockForNetworkAccessLN();
-                }
-            } else {
-                mCurProcStateSeq = procStateSeq;
-                mShouldBlockForNetwork = true;
-                blockForNetworkAccessLN();
-            }
-        }
-    }
-
-    /**
-     * Block for unrestricted network. It will register a listener to AMS and wait for it to
-     * notify that network policy rules are updated. This method is called before relevant app
-     * components are launched.
-     */
-    private void blockForNetworkAccessLN() {
-        try {
-            if (ActivityManager.getService().registerNetworkRulesUpdateListener(
-                    mAppThread, mCurProcStateSeq)) {
-                try {
-                    Slog.d(TAG, "Uid: " + mBoundApplication.appInfo.uid
-                            + " seq: " + mCurProcStateSeq
-                            + ". Blocking for network. callers: " + Debug.getCallers(3));
-                    final long blockStartTime = SystemClock.elapsedRealtime();
-                    mNetworkPolicyLock.wait(mWaitForNetworkTimeoutMs);
-                    final long totalWaitTime = (SystemClock.elapsedRealtime() - blockStartTime);
-                    if (totalWaitTime >= mWaitForNetworkTimeoutMs) {
-                        Slog.wtf(TAG, "Timed out waiting for the network rules to get updated."
-                                + " Uid: " + mBoundApplication.appInfo.uid + " seq: "
-                                + mCurProcStateSeq);
-                    } else if (totalWaitTime >= WAIT_FOR_NETWORK_THRESHOLD_MS) {
-                        Slog.d(TAG, "Waited for time greater than threshold."
-                                + " Uid: " + mBoundApplication.appInfo.uid + " seq: "
-                                + mCurProcStateSeq);
-                    }
-                    if (DEBUG_NETWORK) {
-                        Slog.d(TAG, "Uid: " + mBoundApplication.appInfo.uid
-                                + " seq: " + mCurProcStateSeq
-                                + ". Time waited for network: " + totalWaitTime);
-                    }
-                } catch (InterruptedException ignored) {
-                }
-            }
-        } catch (RemoteException ignored) {
-        }
-    }
-
-    public void checkAndBlockForNetworkAccess() {
-        synchronized (mNetworkPolicyLock) {
-            if (mWaitForNetworkTimeoutMs > 0 && mShouldBlockForNetwork) {
-                blockForNetworkAccessLN();
-            }
-        }
-    }
-
-    /**
-     * Unblock the main thread if it is waiting for network.
-     */
-    private void unblockForNetworkAccessLN(long procStateSeq) {
-        if (mShouldBlockForNetwork && procStateSeq >= mCurProcStateSeq) {
-            if (DEBUG_NETWORK) {
-                Slog.d(TAG, "Unblocking threads waiting for network. uid: "
-                        + mBoundApplication.appInfo.uid + " procStateSeq: " + procStateSeq);
-            }
-            mNetworkPolicyLock.notifyAll();
-            mShouldBlockForNetwork = false;
-        }
-    }
-
     ActivityThread() {
         mResourcesManager = ResourcesManager.getInstance();
     }
@@ -2828,7 +2686,6 @@
                     activity.mIntent = customIntent;
                 }
                 r.lastNonConfigurationInstances = null;
-                checkAndBlockForNetworkAccess();
                 activity.mStartedActivity = false;
                 int theme = r.activityInfo.getThemeResource();
                 if (theme != 0) {
@@ -2916,7 +2773,7 @@
             for (int id : dm.getDisplayIds()) {
                 if (id != Display.DEFAULT_DISPLAY) {
                     Display display =
-                            dm.getCompatibleDisplay(id, appContext.getDisplayAdjustments(id));
+                            dm.getCompatibleDisplay(id, appContext.getResources());
                     appContext = (ContextImpl) appContext.createDisplayContext(display);
                     break;
                 }
@@ -5113,7 +4970,7 @@
             LoadedApk apk = ref != null ? ref.get() : null;
             if (apk != null) {
                 final ArrayList<String> oldPaths = new ArrayList<>();
-                LoadedApk.makePaths(this, apk.getApplicationInfo(), oldPaths, null /*outLibPaths*/);
+                LoadedApk.makePaths(this, apk.getApplicationInfo(), oldPaths);
                 apk.updateApplicationInfo(ai, oldPaths);
             }
 
@@ -5121,7 +4978,7 @@
             apk = ref != null ? ref.get() : null;
             if (apk != null) {
                 final ArrayList<String> oldPaths = new ArrayList<>();
-                LoadedApk.makePaths(this, apk.getApplicationInfo(), oldPaths, null /*outLibPaths*/);
+                LoadedApk.makePaths(this, apk.getApplicationInfo(), oldPaths);
                 apk.updateApplicationInfo(ai, oldPaths);
             }
 
@@ -5564,9 +5421,6 @@
         View.mDebugViewAttributes =
                 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0;
 
-        mWaitForNetworkTimeoutMs = mCoreSettings.getLong(
-                Settings.Global.WAIT_FOR_NETWORK_TIMEOUT_MS);
-
         /**
          * For system applications on userdebug/eng builds, log stack
          * traces of disk and network access to dropbox for analysis.
diff --git a/core/java/android/app/ContextImpl.java b/core/java/android/app/ContextImpl.java
index 045bd0a..3e9b987 100644
--- a/core/java/android/app/ContextImpl.java
+++ b/core/java/android/app/ContextImpl.java
@@ -2067,24 +2067,17 @@
 
     @Override
     public Display getDisplay() {
-        final DisplayAdjustments displayAdjustments = mResources.getDisplayAdjustments();
         if (mDisplay == null) {
             return mResourcesManager.getAdjustedDisplay(Display.DEFAULT_DISPLAY,
-                    displayAdjustments);
+                    mResources);
         }
 
-        if (!mDisplay.getDisplayAdjustments().equals(displayAdjustments)) {
-            mDisplay = mResourcesManager.getAdjustedDisplay(mDisplay.getDisplayId(),
-                    displayAdjustments);
-        }
         return mDisplay;
     }
 
     @Override
     public void updateDisplay(int displayId) {
-        final DisplayAdjustments displayAdjustments = mResources.getDisplayAdjustments();
-        mDisplay = mResourcesManager.getAdjustedDisplay(displayId,
-                displayAdjustments);
+        mDisplay = mResourcesManager.getAdjustedDisplay(displayId, mResources);
     }
 
     @Override
@@ -2202,7 +2195,7 @@
                 compatInfo,
                 classLoader);
         context.mDisplay = resourcesManager.getAdjustedDisplay(displayId,
-                context.mResources.getDisplayAdjustments());
+                context.getResources());
         return context;
     }
 
diff --git a/core/java/android/app/FragmentManager.java b/core/java/android/app/FragmentManager.java
index 8ad7810..977931a 100644
--- a/core/java/android/app/FragmentManager.java
+++ b/core/java/android/app/FragmentManager.java
@@ -397,6 +397,19 @@
     public void invalidateOptionsMenu() { }
 
     /**
+     * Returns {@code true} if the FragmentManager's state has already been saved
+     * by its host. Any operations that would change saved state should not be performed
+     * if this method returns true. For example, any popBackStack() method, such as
+     * {@link #popBackStackImmediate()} or any FragmentTransaction using
+     * {@link FragmentTransaction#commit()} instead of
+     * {@link FragmentTransaction#commitAllowingStateLoss()} will change
+     * the state and will result in an error.
+     *
+     * @return true if this FragmentManager's state has already been saved by its host
+     */
+    public abstract boolean isStateSaved();
+
+    /**
      * Callback interface for listening to fragment state changes that happen
      * within a given FragmentManager.
      */
@@ -1787,6 +1800,7 @@
         }
     }
 
+    @Override
     public boolean isStateSaved() {
         return mStateSaved;
     }
diff --git a/core/java/android/app/IActivityManager.aidl b/core/java/android/app/IActivityManager.aidl
index 6717491..8538330 100644
--- a/core/java/android/app/IActivityManager.aidl
+++ b/core/java/android/app/IActivityManager.aidl
@@ -199,7 +199,7 @@
     int getRequestedOrientation(in IBinder token);
     void unbindFinished(in IBinder token, in Intent service, boolean doRebind);
     void setProcessForeground(in IBinder token, int pid, boolean isForeground);
-    long setServiceForeground(in ComponentName className, in IBinder token,
+    void setServiceForeground(in ComponentName className, in IBinder token,
             int id, in Notification notification, int flags);
     boolean moveActivityTaskToBack(in IBinder token, boolean nonRoot);
     void getMemoryInfo(out ActivityManager.MemoryInfo outInfo);
@@ -604,16 +604,6 @@
     ActivityManager.TaskSnapshot getTaskSnapshot(int taskId);
 
     void scheduleApplicationInfoChanged(in List<String> packageNames, int userId);
-     /**
-      * Registers a listener for network rules state. When the network policy rules in
-      * NetworkPolicyManagerService are updated, ActivityManagerService will notify these
-      * registered listeners.
-      *
-      * @param procStateSeq The sequence number for which the listener is interested in knowing
-      *                     the network policy rules state.
-      * @return true if the listener is registered, false otherwise.
-      */
-    boolean registerNetworkRulesUpdateListener(IApplicationThread listener, long procStateSeq);
 
     // WARNING: when these transactions are updated, check if they are any callers on the native
     // side. If so, make sure they are using the correct transaction ids and arguments.
diff --git a/core/java/android/app/IApplicationThread.aidl b/core/java/android/app/IApplicationThread.aidl
index 1735572..d5b4668 100644
--- a/core/java/android/app/IApplicationThread.aidl
+++ b/core/java/android/app/IApplicationThread.aidl
@@ -154,6 +154,4 @@
     void handleTrustStorageUpdate();
     void attachAgent(String path);
     void scheduleApplicationInfoChanged(in ApplicationInfo ai);
-    void setBlockForNetworkState(int blockState, long procStateSeq);
-    void notifyNetworkStateUpdated(long procStateSeq);
 }
diff --git a/core/java/android/app/LoadedApk.java b/core/java/android/app/LoadedApk.java
index 7ed96af..1c33e38 100644
--- a/core/java/android/app/LoadedApk.java
+++ b/core/java/android/app/LoadedApk.java
@@ -278,7 +278,7 @@
         setApplicationInfo(aInfo);
 
         final List<String> newPaths = new ArrayList<>();
-        makePaths(mActivityThread, aInfo, newPaths, null /*libPaths*/);
+        makePaths(mActivityThread, aInfo, newPaths);
         final List<String> addedPaths = new ArrayList<>(newPaths.size());
 
         if (oldPaths != null) {
@@ -341,8 +341,17 @@
         }
     }
 
-    public static void makePaths(ActivityThread activityThread, ApplicationInfo aInfo,
-            List<String> outZipPaths, List<String> outLibPaths) {
+    public static void makePaths(ActivityThread activityThread,
+                                 ApplicationInfo aInfo,
+                                 List<String> outZipPaths) {
+        makePaths(activityThread, false, aInfo, outZipPaths, null);
+    }
+
+    public static void makePaths(ActivityThread activityThread,
+                                 boolean isBundledApp,
+                                 ApplicationInfo aInfo,
+                                 List<String> outZipPaths,
+                                 List<String> outLibPaths) {
         final String appDir = aInfo.sourceDir;
         final String libDir = aInfo.nativeLibraryDir;
         final String[] sharedLibraries = aInfo.sharedLibraryFiles;
@@ -431,7 +440,7 @@
                 }
             }
 
-            if (aInfo.isSystemApp() && !aInfo.isUpdatedSystemApp()) {
+            if (isBundledApp) {
                 // Add path to system libraries to libPaths;
                 // Access to system libs should be limited
                 // to bundled applications; this is why updated
@@ -614,11 +623,12 @@
         // space and initialize to a small value (instead of incurring growth code).
         final List<String> zipPaths = new ArrayList<>(10);
         final List<String> libPaths = new ArrayList<>(10);
-        makePaths(mActivityThread, mApplicationInfo, zipPaths, libPaths);
 
         final boolean isBundledApp = mApplicationInfo.isSystemApp()
                 && !mApplicationInfo.isUpdatedSystemApp();
 
+        makePaths(mActivityThread, isBundledApp, mApplicationInfo, zipPaths, libPaths);
+
         String libraryPermittedPath = mDataDir;
         if (isBundledApp) {
             // This is necessary to grant bundled apps access to
diff --git a/core/java/android/app/ResourcesManager.java b/core/java/android/app/ResourcesManager.java
index 55f7df3..52ec045 100644
--- a/core/java/android/app/ResourcesManager.java
+++ b/core/java/android/app/ResourcesManager.java
@@ -104,10 +104,17 @@
             new WeakHashMap<>();
 
     /**
-     * A cache of DisplayId to DisplayAdjustments.
+     * A cache of DisplayId, DisplayAdjustments to Display.
      */
-    private final ArrayMap<Pair<Integer, DisplayAdjustments>, WeakReference<Display>> mDisplays =
-            new ArrayMap<>();
+    private final ArrayMap<Pair<Integer, DisplayAdjustments>, WeakReference<Display>>
+            mAdjustedDisplays = new ArrayMap<>();
+
+    /**
+     * A cache of DisplayId, Resources to Display. These display adjustments associated with these
+     * {@link Display}s will change as the resources change.
+     */
+    private final ArrayMap<Pair<Integer, Resources>, WeakReference<Display>> mResourceDisplays =
+        new ArrayMap<>();
 
     public static ResourcesManager getInstance() {
         synchronized (ResourcesManager.class) {
@@ -201,19 +208,21 @@
 
     /**
      * Returns an adjusted {@link Display} object based on the inputs or null if display isn't
-     * available.
+     * available. This method is only used within {@link ResourcesManager} to calculate display
+     * metrics based on a set {@link DisplayAdjustments}. All other usages should instead call
+     * {@link ResourcesManager#getAdjustedDisplay(int, Resources)}.
      *
      * @param displayId display Id.
      * @param displayAdjustments display adjustments.
      */
-    public Display getAdjustedDisplay(final int displayId,
+    private Display getAdjustedDisplay(final int displayId,
             @Nullable DisplayAdjustments displayAdjustments) {
         final DisplayAdjustments displayAdjustmentsCopy = (displayAdjustments != null)
                 ? new DisplayAdjustments(displayAdjustments) : new DisplayAdjustments();
         final Pair<Integer, DisplayAdjustments> key =
                 Pair.create(displayId, displayAdjustmentsCopy);
         synchronized (this) {
-            WeakReference<Display> wd = mDisplays.get(key);
+            WeakReference<Display> wd = mAdjustedDisplays.get(key);
             if (wd != null) {
                 final Display display = wd.get();
                 if (display != null) {
@@ -227,7 +236,37 @@
             }
             final Display display = dm.getCompatibleDisplay(displayId, key.second);
             if (display != null) {
-                mDisplays.put(key, new WeakReference<>(display));
+                mAdjustedDisplays.put(key, new WeakReference<>(display));
+            }
+            return display;
+        }
+    }
+
+    /**
+     * Returns an adjusted {@link Display} object based on the inputs or null if display isn't
+     * available.
+     *
+     * @param displayId display Id.
+     * @param resources The {@link Resources} backing the display adjustments.
+     */
+    public Display getAdjustedDisplay(final int displayId, Resources resources) {
+        final Pair<Integer, Resources> key = Pair.create(displayId, resources);
+        synchronized (this) {
+            WeakReference<Display> wd = mResourceDisplays.get(key);
+            if (wd != null) {
+                final Display display = wd.get();
+                if (display != null) {
+                    return display;
+                }
+            }
+            final DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
+            if (dm == null) {
+                // may be null early in system startup
+                return null;
+            }
+            final Display display = dm.getCompatibleDisplay(displayId, resources);
+            if (display != null) {
+                mResourceDisplays.put(key, new WeakReference<>(display));
             }
             return display;
         }
@@ -316,6 +355,7 @@
         final DisplayMetrics dm = getDisplayMetrics(key.mDisplayId, daj);
         final Configuration config = generateConfig(key, dm);
         final ResourcesImpl impl = new ResourcesImpl(assets, dm, config, daj);
+
         if (DEBUG) {
             Slog.d(TAG, "- creating impl=" + impl + " with key: " + key);
         }
@@ -811,7 +851,9 @@
             }
             int changes = mResConfiguration.updateFrom(config);
             // Things might have changed in display manager, so clear the cached displays.
-            mDisplays.clear();
+            mAdjustedDisplays.clear();
+            mResourceDisplays.clear();
+
             DisplayMetrics defaultDisplayMetrics = getDisplayMetrics();
 
             if (compat != null && (mResCompatibilityInfo == null ||
diff --git a/core/java/android/app/Service.java b/core/java/android/app/Service.java
index 9cd048e..4fe4f98 100644
--- a/core/java/android/app/Service.java
+++ b/core/java/android/app/Service.java
@@ -683,28 +683,26 @@
      * flag if killing your service would be disruptive to the user, such as
      * if your service is performing background music playback, so the user
      * would notice if their music stopped playing.
-     *
+     * 
      * <p>If you need your application to run on platform versions prior to API
      * level 5, you can use the following model to call the the older setForeground()
      * or this modern method as appropriate:
-     *
+     * 
      * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/ForegroundService.java
      *   foreground_compatibility}
-     *
+     * 
      * @param id The identifier for this notification as per
      * {@link NotificationManager#notify(int, Notification)
      * NotificationManager.notify(int, Notification)}; must not be 0.
      * @param notification The Notification to be displayed.
-     *
+     * 
      * @see #stopForeground(boolean)
      */
     public final void startForeground(int id, Notification notification) {
         try {
-            final long procStateSeq = mActivityManager.setServiceForeground(
-                    new ComponentName(this, mClassName), mToken, id, notification, 0);
-            if (procStateSeq != ActivityThread.INVALID_PROC_STATE_SEQ && mThread != null) {
-                mThread.blockForNetworkAccessInForegroundService(procStateSeq);
-            }
+            mActivityManager.setServiceForeground(
+                    new ComponentName(this, mClassName), mToken, id,
+                    notification, 0);
         } catch (RemoteException ex) {
         }
     }
diff --git a/core/java/android/app/assist/AssistStructure.java b/core/java/android/app/assist/AssistStructure.java
index 678c017..483a7a1 100644
--- a/core/java/android/app/assist/AssistStructure.java
+++ b/core/java/android/app/assist/AssistStructure.java
@@ -538,6 +538,7 @@
         AutoFillId mAutoFillId;
         AutoFillType mAutoFillType;
         AutoFillValue mAutoFillValue;
+        String[] mAutoFillOptions;
         boolean mSanitized;
         int mX;
         int mY;
@@ -618,6 +619,7 @@
                 mAutoFillId = in.readParcelable(null);
                 mAutoFillType = in.readParcelable(null);
                 mAutoFillValue = in.readParcelable(null);
+                mAutoFillOptions = in.readStringArray();
             }
             if ((flags&FLAGS_HAS_LARGE_COORDS) != 0) {
                 mX = in.readInt();
@@ -720,7 +722,14 @@
             }
 
             pwriter.writeString(mClassName);
-            out.writeInt(flags);
+
+            int writtenFlags = flags;
+            if ((flags&FLAGS_HAS_AUTO_FILL_DATA) != 0 && (mSanitized || !sanitizeOnWrite)) {
+                // Remove 'checked' from sanitized auto-fill request.
+                writtenFlags = flags & ~FLAGS_CHECKED;
+            }
+
+            out.writeInt(writtenFlags);
             if ((flags&FLAGS_HAS_ID) != 0) {
                 out.writeInt(mId);
                 if (mId != 0) {
@@ -738,6 +747,7 @@
                 out.writeParcelable(mAutoFillType,  0);
                 final AutoFillValue sanitizedValue = writeSensitive ? mAutoFillValue : null;
                 out.writeParcelable(sanitizedValue,  0);
+                out.writeStringArray(mAutoFillOptions);
             }
             if ((flags&FLAGS_HAS_LARGE_COORDS) != 0) {
                 out.writeInt(mX);
@@ -844,6 +854,19 @@
             return mAutoFillValue;
         }
 
+        /**
+         * Gets the options that can be used to auto-fill this structure.
+         *
+         * <p>Typically used by nodes whose {@link AutoFillType} is a list to indicate the meaning
+         * of each possible value in the list.
+         *
+         * <p>It's only set when the {@link AssistStructure} is used for auto-filling purposes, not
+         * for assist.
+         */
+        public String[] getAutoFillOptions() {
+            return mAutoFillOptions;
+        }
+
         /** @hide */
         public boolean isSanitized() {
             return mSanitized;
@@ -1506,6 +1529,11 @@
             mNode.mAutoFillValue = value;
         }
 
+        @Override
+        public void setAutoFillOptions(String[] options) {
+            mNode.mAutoFillOptions = options;
+        }
+
         /**
          * @hide
          */
diff --git a/core/java/android/app/usage/IStorageStatsManager.aidl b/core/java/android/app/usage/IStorageStatsManager.aidl
index f4c18dd..76c0293 100644
--- a/core/java/android/app/usage/IStorageStatsManager.aidl
+++ b/core/java/android/app/usage/IStorageStatsManager.aidl
@@ -24,6 +24,7 @@
     boolean isQuotaSupported(String volumeUuid, String callingPackage);
     long getTotalBytes(String volumeUuid, String callingPackage);
     long getFreeBytes(String volumeUuid, String callingPackage);
+    StorageStats queryStatsForPackage(String volumeUuid, String packageName, int userId, String callingPackage);
     StorageStats queryStatsForUid(String volumeUuid, int uid, String callingPackage);
     StorageStats queryStatsForUser(String volumeUuid, int userId, String callingPackage);
     ExternalStorageStats queryExternalStatsForUser(String volumeUuid, int userId, String callingPackage);
diff --git a/core/java/android/app/usage/StorageStatsManager.java b/core/java/android/app/usage/StorageStatsManager.java
index 7d4efb9..081ccd9 100644
--- a/core/java/android/app/usage/StorageStatsManager.java
+++ b/core/java/android/app/usage/StorageStatsManager.java
@@ -19,6 +19,7 @@
 import android.annotation.WorkerThread;
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
 import android.os.RemoteException;
 import android.os.UserHandle;
 
@@ -100,6 +101,37 @@
     }
 
     /**
+     * Return storage statistics for a specific package on the requested storage
+     * volume.
+     * <p>
+     * This method may take several seconds to calculate the requested values,
+     * so it should only be called from a worker thread.
+     * <p class="note">
+     * Note: if the requested package uses the {@code android:sharedUserId}
+     * manifest feature, this call will be forced into a slower manual
+     * calculation path. If possible, consider always using
+     * {@link #queryStatsForUid(String, int)}, which is typically faster.
+     * </p>
+     *
+     * @param volumeUuid the UUID of the storage volume you're interested in, or
+     *            {@code null} to specify the default internal storage.
+     * @param packageName the package name you're interested in.
+     * @param user the user you're interested in.
+     * @see ApplicationInfo#volumeUuid
+     * @see PackageInfo#packageName
+     */
+    @WorkerThread
+    public StorageStats queryStatsForPackage(String volumeUuid, String packageName,
+            UserHandle user) {
+        try {
+            return mService.queryStatsForPackage(volumeUuid, packageName, user.getIdentifier(),
+                    mContext.getOpPackageName());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
      * Return storage statistics for a specific UID on the requested storage
      * volume.
      * <p>
diff --git a/core/java/android/hardware/display/DisplayManager.java b/core/java/android/hardware/display/DisplayManager.java
index 33a9f5e..a529c2f 100644
--- a/core/java/android/hardware/display/DisplayManager.java
+++ b/core/java/android/hardware/display/DisplayManager.java
@@ -339,8 +339,7 @@
     private Display getOrCreateDisplayLocked(int displayId, boolean assumeValid) {
         Display display = mDisplays.get(displayId);
         if (display == null) {
-            display = mGlobal.getCompatibleDisplay(displayId,
-                    mContext.getDisplayAdjustments(displayId));
+            display = mGlobal.getCompatibleDisplay(displayId, mContext.getResources());
             if (display != null) {
                 mDisplays.put(displayId, display);
             }
diff --git a/core/java/android/hardware/display/DisplayManagerGlobal.java b/core/java/android/hardware/display/DisplayManagerGlobal.java
index 826eb74..341754c 100644
--- a/core/java/android/hardware/display/DisplayManagerGlobal.java
+++ b/core/java/android/hardware/display/DisplayManagerGlobal.java
@@ -18,6 +18,7 @@
 
 import android.content.Context;
 import android.content.res.Configuration;
+import android.content.res.Resources;
 import android.hardware.display.DisplayManager.DisplayListener;
 import android.media.projection.MediaProjection;
 import android.media.projection.IMediaProjection;
@@ -181,6 +182,24 @@
     }
 
     /**
+     * Gets information about a logical display.
+     *
+     * The display metrics may be adjusted to provide compatibility
+     * for legacy applications or limited screen areas.
+     *
+     * @param displayId The logical display id.
+     * @param resources Resources providing compatibility info.
+     * @return The display object, or null if there is no display with the given id.
+     */
+    public Display getCompatibleDisplay(int displayId, Resources resources) {
+        DisplayInfo displayInfo = getDisplayInfo(displayId);
+        if (displayInfo == null) {
+            return null;
+        }
+        return new Display(this, displayId, displayInfo, resources);
+    }
+
+    /**
      * Gets information about a logical display without applying any compatibility metrics.
      *
      * @param displayId The logical display id.
diff --git a/core/java/android/net/ConnectivityMetricsEvent.aidl b/core/java/android/net/ConnectivityMetricsEvent.aidl
index a027d7c..1c541dc 100644
--- a/core/java/android/net/ConnectivityMetricsEvent.aidl
+++ b/core/java/android/net/ConnectivityMetricsEvent.aidl
@@ -16,5 +16,5 @@
 
 package android.net;
 
+/** {@hide} */
 parcelable ConnectivityMetricsEvent;
-parcelable ConnectivityMetricsEvent.Reference;
diff --git a/core/java/android/net/ConnectivityMetricsEvent.java b/core/java/android/net/ConnectivityMetricsEvent.java
index eaaef7f..6fdc739 100644
--- a/core/java/android/net/ConnectivityMetricsEvent.java
+++ b/core/java/android/net/ConnectivityMetricsEvent.java
@@ -16,12 +16,10 @@
 
 package android.net;
 
-import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 
 /** {@hide} */
-@SystemApi
 public final class ConnectivityMetricsEvent implements Parcelable {
 
     /**  The time when this event was collected, as returned by System.currentTimeMillis(). */
@@ -67,7 +65,6 @@
         return 0;
     }
 
-    /** Implement the Parcelable interface */
     @Override
     public void writeToParcel(Parcel dest, int flags) {
         dest.writeLong(timestamp);
@@ -80,51 +77,4 @@
         return String.format("ConnectivityMetricsEvent(%tT.%tL, %d, %d): %s",
                 timestamp, timestamp, componentTag, eventTag, data);
     }
-
-    /** {@hide} */
-    @SystemApi
-    public final static class Reference implements Parcelable {
-
-        private long mValue;
-
-        public Reference(long ref) {
-            this.mValue = ref;
-        }
-
-        /** Implement the Parcelable interface */
-        public static final Parcelable.Creator<Reference> CREATOR
-                = new Parcelable.Creator<Reference> (){
-            public Reference createFromParcel(Parcel source) {
-                return new Reference(source.readLong());
-            }
-
-            public Reference[] newArray(int size) {
-                return new Reference[size];
-            }
-        };
-
-        /** Implement the Parcelable interface */
-        @Override
-        public int describeContents() {
-            return 0;
-        }
-
-        /** Implement the Parcelable interface */
-        @Override
-        public void writeToParcel(Parcel dest, int flags) {
-            dest.writeLong(mValue);
-        }
-
-        public void readFromParcel(Parcel in) {
-            mValue = in.readLong();
-        }
-
-        public long getValue() {
-            return mValue;
-        }
-
-        public void setValue(long val) {
-            mValue = val;
-        }
-    }
 }
diff --git a/core/java/android/net/ConnectivityMetricsLogger.java b/core/java/android/net/ConnectivityMetricsLogger.java
deleted file mode 100644
index 67b6908..0000000
--- a/core/java/android/net/ConnectivityMetricsLogger.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package android.net;
-
-import android.annotation.SystemApi;
-import android.app.PendingIntent;
-import android.os.Bundle;
-import android.os.Parcelable;
-import android.os.RemoteException;
-import android.os.ServiceManager;
-import android.util.Log;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-/** {@hide} */
-@SystemApi
-public class ConnectivityMetricsLogger {
-    private static String TAG = "ConnectivityMetricsLogger";
-    private static final boolean DBG = true;
-
-    public static final String CONNECTIVITY_METRICS_LOGGER_SERVICE = "connectivity_metrics_logger";
-
-    // Component Tags
-    public static final int COMPONENT_TAG_CONNECTIVITY = 0;
-    public static final int COMPONENT_TAG_BLUETOOTH    = 1;
-    public static final int COMPONENT_TAG_WIFI         = 2;
-    public static final int COMPONENT_TAG_TELECOM      = 3;
-    public static final int COMPONENT_TAG_TELEPHONY    = 4;
-    public static final int NUMBER_OF_COMPONENTS       = 5;
-
-    // Event Tag
-    public static final int TAG_SKIPPED_EVENTS = -1;
-
-    public static final String DATA_KEY_EVENTS_COUNT = "count";
-
-    public ConnectivityMetricsLogger() {
-    }
-
-    /**
-     * Log a ConnectivityMetricsEvent.
-     *
-     * This method keeps track of skipped events when MetricsLoggerService throttles input events.
-     * It skips logging when MetricsLoggerService is active. When throttling ends, it logs a
-     * meta-event containing the number of events dropped. It is not safe to call this method
-     * concurrently from different threads.
-     *
-     * @param timestamp is the epoch timestamp of the event in ms.
-     * @param componentTag is the COMPONENT_* constant the event belongs to.
-     * @param eventTag is an event type constant whose meaning is specific to the component tag.
-     * @param data is a Parcelable instance representing the event.
-     */
-    public void logEvent(long timestamp, int componentTag, int eventTag, Parcelable data) {
-    }
-
-    /**
-     * Retrieve events
-     *
-     * @param reference of the last event previously returned. The function will return
-     *                  events following it.
-     *                  If 0 then all events will be returned.
-     *                  After the function call it will contain reference of the
-     *                  last returned event.
-     * @return events
-     */
-    public ConnectivityMetricsEvent[] getEvents(ConnectivityMetricsEvent.Reference reference) {
-        return new ConnectivityMetricsEvent[0];
-    }
-
-    /**
-     * Register PendingIntent which will be sent when new events are ready to be retrieved.
-     */
-    public boolean register(PendingIntent newEventsIntent) {
-        return false;
-    }
-
-    public boolean unregister(PendingIntent newEventsIntent) {
-        return false;
-    }
-}
diff --git a/core/java/android/net/IConnectivityMetricsLogger.aidl b/core/java/android/net/IConnectivityMetricsLogger.aidl
deleted file mode 100644
index a83a019..0000000
--- a/core/java/android/net/IConnectivityMetricsLogger.aidl
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.net;
-
-import android.app.PendingIntent;
-import android.net.ConnectivityMetricsEvent;
-
-/** {@hide} */
-interface IConnectivityMetricsLogger {
-
-    /**
-     * @return 0 on success
-     *        <0 if error happened
-     *        >0 timestamp after which new events will be accepted
-     */
-    long logEvent(in ConnectivityMetricsEvent event);
-    long logEvents(in ConnectivityMetricsEvent[] events);
-
-    /**
-     * @param reference of the last event previously returned. The function will return
-     *                  events following it.
-     *                  If 0 then all events will be returned.
-     *                  After the function call it will contain reference of the last event.
-     */
-    ConnectivityMetricsEvent[] getEvents(inout ConnectivityMetricsEvent.Reference reference);
-
-    boolean register(in PendingIntent newEventsIntent);
-    void unregister(in PendingIntent newEventsIntent);
-}
diff --git a/core/java/android/net/NetworkPolicyManager.java b/core/java/android/net/NetworkPolicyManager.java
index 4b184f1..1b715af 100644
--- a/core/java/android/net/NetworkPolicyManager.java
+++ b/core/java/android/net/NetworkPolicyManager.java
@@ -19,7 +19,6 @@
 import static android.content.pm.PackageManager.GET_SIGNATURES;
 import static android.net.NetworkPolicy.CYCLE_NONE;
 
-import android.app.ActivityManager;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
@@ -66,8 +65,6 @@
      *
      * See network-policy-restrictions.md for more info.
      */
-    /** Not a valid rule */
-    public static final int RULE_INVALID = -1;
     /** No specific rule was set */
     public static final int RULE_NONE = 0;
     /** Allow traffic on metered networks. */
@@ -363,8 +360,6 @@
         final StringBuilder string = new StringBuilder().append(uidRules).append(" (");
         if (uidRules == RULE_NONE) {
             string.append("NONE");
-        } else if (uidRules == RULE_INVALID) {
-            string.append("INVALID");
         } else {
             string.append(DebugUtils.flagsToString(NetworkPolicyManager.class, "RULE_", uidRules));
         }
@@ -386,25 +381,4 @@
         string.append(")");
         return string.toString();
     }
-
-    /**
-     * @hide
-     */
-    public static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
-        return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
-    }
-
-    /**
-     * @hide
-     */
-    public static boolean isProcStateAllowedWhileRestrictBackgroundOn(int procState) {
-        return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
-    }
-
-    /**
-     * @hide
-     */
-    public interface UidStateWithSeqObserver {
-        void onUidStateChangedWithSeq(int uid, int procState, long seq);
-    }
 }
diff --git a/core/java/android/net/NetworkScoreManager.java b/core/java/android/net/NetworkScoreManager.java
index 8f3af66..edfaee4 100644
--- a/core/java/android/net/NetworkScoreManager.java
+++ b/core/java/android/net/NetworkScoreManager.java
@@ -96,17 +96,24 @@
     public static final String EXTRA_NETWORKS_TO_SCORE = "networksToScore";
 
     /**
-     * Activity action: launch a custom activity for configuring a scorer before enabling it.
-     * Scorer applications may choose to specify an activity for this action, in which case the
-     * framework will launch that activity which should return RESULT_OK if scoring was enabled.
-     *
-     * <p>If no activity is included in a scorer which implements this action, the system dialog for
-     * selecting a scorer will be shown instead.
+     * Activity action: launch an activity for configuring a provider for the feature that connects
+     * and secures open wifi networks available before enabling it. Applications that enable this
+     * feature must provide an activity for this action. The framework will launch this activity
+     * which must return RESULT_OK if the feature should be enabled.
      */
     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
     public static final String ACTION_CUSTOM_ENABLE = "android.net.scoring.CUSTOM_ENABLE";
 
     /**
+     * Meta-data specified on a {@link NetworkRecommendationProvider} that specified the package
+     * name of the application that connects and secures open wifi networks automatically. The
+     * specified package must provide an Activity for {@link #ACTION_CUSTOM_ENABLE}.
+     * @hide
+     */
+    public static final String USE_OPEN_WIFI_PACKAGE_META_DATA =
+            "android.net.wifi.use_open_wifi_package";
+
+    /**
      * Broadcast action: the active scorer has been changed. Scorer apps may listen to this to
      * perform initialization once selected as the active scorer, or clean up unneeded resources
      * if another scorer has been selected. This is an explicit broadcast only sent to the
diff --git a/core/java/android/net/NetworkScorerAppManager.java b/core/java/android/net/NetworkScorerAppManager.java
index a166c7f..bbc1c79 100644
--- a/core/java/android/net/NetworkScorerAppManager.java
+++ b/core/java/android/net/NetworkScorerAppManager.java
@@ -26,6 +26,7 @@
 import android.content.pm.ResolveInfo;
 import android.os.Parcel;
 import android.os.Parcelable;
+import android.content.pm.ServiceInfo;
 import android.os.UserHandle;
 import android.provider.Settings;
 import android.text.TextUtils;
@@ -60,21 +61,30 @@
         /** UID of the scorer app. */
         public final int packageUid;
         private final ComponentName mRecommendationService;
+        /**
+         * The {@link ComponentName} of the Activity to start before enabling the "connect to open
+         * wifi networks automatically" feature.
+         */
+        private final ComponentName mEnableUseOpenWifiActivity;
 
-        public NetworkScorerAppData(int packageUid, ComponentName recommendationServiceComp) {
+        public NetworkScorerAppData(int packageUid, ComponentName recommendationServiceComp,
+                ComponentName enableUseOpenWifiActivity) {
             this.packageUid = packageUid;
             this.mRecommendationService = recommendationServiceComp;
+            this.mEnableUseOpenWifiActivity = enableUseOpenWifiActivity;
         }
 
         protected NetworkScorerAppData(Parcel in) {
             packageUid = in.readInt();
             mRecommendationService = ComponentName.readFromParcel(in);
+            mEnableUseOpenWifiActivity = ComponentName.readFromParcel(in);
         }
 
         @Override
         public void writeToParcel(Parcel dest, int flags) {
             dest.writeInt(packageUid);
             ComponentName.writeToParcel(mRecommendationService, dest);
+            ComponentName.writeToParcel(mEnableUseOpenWifiActivity, dest);
         }
 
         @Override
@@ -103,11 +113,16 @@
             return mRecommendationService;
         }
 
+        @Nullable public ComponentName getEnableUseOpenWifiActivity() {
+            return mEnableUseOpenWifiActivity;
+        }
+
         @Override
         public String toString() {
             return "NetworkScorerAppData{" +
                     "packageUid=" + packageUid +
                     ", mRecommendationService=" + mRecommendationService +
+                    ", mEnableUseOpenWifiActivity=" + mEnableUseOpenWifiActivity +
                     '}';
         }
 
@@ -117,12 +132,13 @@
             if (o == null || getClass() != o.getClass()) return false;
             NetworkScorerAppData that = (NetworkScorerAppData) o;
             return packageUid == that.packageUid &&
-                    Objects.equals(mRecommendationService, that.mRecommendationService);
+                    Objects.equals(mRecommendationService, that.mRecommendationService) &&
+                    Objects.equals(mEnableUseOpenWifiActivity, that.mEnableUseOpenWifiActivity);
         }
 
         @Override
         public int hashCode() {
-            return Objects.hash(packageUid, mRecommendationService);
+            return Objects.hash(packageUid, mRecommendationService, mEnableUseOpenWifiActivity);
         }
     }
 
@@ -165,12 +181,14 @@
             final String potentialPkg = potentialPkgs.get(i);
 
             // Look for the recommendation service class and required receiver.
-            final ResolveInfo resolveServiceInfo = findRecommendationService(potentialPkg);
-            if (resolveServiceInfo != null) {
-                final ComponentName componentName =
-                        new ComponentName(potentialPkg, resolveServiceInfo.serviceInfo.name);
-                return new NetworkScorerAppData(resolveServiceInfo.serviceInfo.applicationInfo.uid,
-                        componentName);
+            final ServiceInfo serviceInfo = findRecommendationService(potentialPkg);
+            if (serviceInfo != null) {
+                final ComponentName serviceComponentName =
+                    new ComponentName(potentialPkg, serviceInfo.name);
+                final ComponentName useOpenWifiNetworksActivity =
+                        findUseOpenWifiNetworksActivity(serviceInfo);
+                return new NetworkScorerAppData(serviceInfo.applicationInfo.uid,
+                    serviceComponentName, useOpenWifiNetworksActivity);
             } else {
                 if (DEBUG) {
                     Log.d(TAG, potentialPkg + " does not have the required components, skipping.");
@@ -182,6 +200,36 @@
         return null;
     }
 
+    @Nullable private ComponentName findUseOpenWifiNetworksActivity(ServiceInfo serviceInfo) {
+        if (serviceInfo.metaData == null) {
+            if (DEBUG) {
+                Log.d(TAG, "No metadata found on recommendation service.");
+            }
+            return null;
+        }
+        final String useOpenWifiPackage = serviceInfo.metaData
+                .getString(NetworkScoreManager.USE_OPEN_WIFI_PACKAGE_META_DATA);
+        if (TextUtils.isEmpty(useOpenWifiPackage)) {
+            if (DEBUG) {
+                Log.d(TAG, "No use_open_wifi_package metadata found.");
+            }
+            return null;
+        }
+        final Intent enableUseOpenWifiIntent = new Intent(NetworkScoreManager.ACTION_CUSTOM_ENABLE)
+                .setPackage(useOpenWifiPackage);
+        final ResolveInfo resolveActivityInfo = mContext.getPackageManager()
+                .resolveActivity(enableUseOpenWifiIntent, 0 /* flags */);
+        if (VERBOSE) {
+            Log.d(TAG, "Resolved " + enableUseOpenWifiIntent + " to " + serviceInfo);
+        }
+
+        if (resolveActivityInfo != null && resolveActivityInfo.activityInfo != null) {
+            return resolveActivityInfo.activityInfo.getComponentName();
+        }
+
+        return null;
+    }
+
     /**
      * @return A priority order list of package names that have been granted the
      *         permission needed for them to act as a network recommendation provider.
@@ -220,10 +268,9 @@
         return packages;
     }
 
-    private ResolveInfo findRecommendationService(String packageName) {
+    @Nullable private ServiceInfo findRecommendationService(String packageName) {
         final PackageManager pm = mContext.getPackageManager();
-        final int resolveFlags = 0;
-
+        final int resolveFlags = PackageManager.GET_META_DATA;
         final Intent serviceIntent = new Intent(NetworkScoreManager.ACTION_RECOMMEND_NETWORKS);
         serviceIntent.setPackage(packageName);
         final ResolveInfo resolveServiceInfo =
@@ -234,7 +281,7 @@
         }
 
         if (resolveServiceInfo != null && resolveServiceInfo.serviceInfo != null) {
-            return resolveServiceInfo;
+            return resolveServiceInfo.serviceInfo;
         }
 
         if (VERBOSE) {
diff --git a/core/java/android/net/http/SslCertificate.java b/core/java/android/net/http/SslCertificate.java
index 2715af0..4c0f418 100644
--- a/core/java/android/net/http/SslCertificate.java
+++ b/core/java/android/net/http/SslCertificate.java
@@ -506,6 +506,6 @@
         if (certificateDate == null) {
             return "";
         }
-        return DateFormat.getDateFormat(context).format(certificateDate);
+        return DateFormat.getMediumDateFormat(context).format(certificateDate);
     }
 }
diff --git a/core/java/android/net/metrics/ApfProgramEvent.java b/core/java/android/net/metrics/ApfProgramEvent.java
index 258d8e1..c2795a2a 100644
--- a/core/java/android/net/metrics/ApfProgramEvent.java
+++ b/core/java/android/net/metrics/ApfProgramEvent.java
@@ -17,7 +17,6 @@
 package android.net.metrics;
 
 import android.annotation.IntDef;
-import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.text.TextUtils;
@@ -36,7 +35,6 @@
  * the APF program in place with a new APF program.
  * {@hide}
  */
-@SystemApi
 public final class ApfProgramEvent implements Parcelable {
 
     // Bitflag constants describing what an Apf program filters.
@@ -55,7 +53,6 @@
     public final int programLength; // Length of the APF program in bytes
     public final int flags;         // Bitfield compound of FLAG_* constants
 
-    /** {@hide} */
     public ApfProgramEvent(
             long lifetime, int filteredRas, int currentRas, int programLength, @Flags int flags) {
         this.lifetime = lifetime;
@@ -105,7 +102,6 @@
         }
     };
 
-    /** {@hide} */
     public static @Flags int flagsFor(boolean hasIPv4, boolean multicastFilterOn) {
         int bitfield = 0;
         if (hasIPv4) {
diff --git a/core/java/android/net/metrics/ApfStats.java b/core/java/android/net/metrics/ApfStats.java
index 8451e53..f8d7fa9 100644
--- a/core/java/android/net/metrics/ApfStats.java
+++ b/core/java/android/net/metrics/ApfStats.java
@@ -16,7 +16,6 @@
 
 package android.net.metrics;
 
-import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 
@@ -24,7 +23,6 @@
  * An event logged for an interface with APF capabilities when its IpManager state machine exits.
  * {@hide}
  */
-@SystemApi
 public final class ApfStats implements Parcelable {
 
     public final long durationMs;     // time interval in milliseconds these stastistics covers
@@ -36,7 +34,6 @@
     public final int programUpdates;  // number of APF program updates
     public final int maxProgramSize;  // maximum APF program size advertised by hardware
 
-    /** {@hide} */
     public ApfStats(long durationMs, int receivedRas, int matchingRas, int droppedRas,
             int zeroLifetimeRas, int parseErrors, int programUpdates, int maxProgramSize) {
         this.durationMs = durationMs;
diff --git a/core/java/android/net/metrics/DefaultNetworkEvent.java b/core/java/android/net/metrics/DefaultNetworkEvent.java
index 9f0bad7..28cf42f 100644
--- a/core/java/android/net/metrics/DefaultNetworkEvent.java
+++ b/core/java/android/net/metrics/DefaultNetworkEvent.java
@@ -16,7 +16,6 @@
 
 package android.net.metrics;
 
-import android.annotation.SystemApi;
 import android.net.NetworkCapabilities;
 import android.os.Parcel;
 import android.os.Parcelable;
@@ -25,7 +24,6 @@
  * An event recorded by ConnectivityService when there is a change in the default network.
  * {@hide}
  */
-@SystemApi
 public final class DefaultNetworkEvent implements Parcelable {
     // The ID of the network that has become the new default or NETID_UNSET if none.
     public final int netId;
@@ -38,7 +36,6 @@
     public final boolean prevIPv4;
     public final boolean prevIPv6;
 
-    /** {@hide} */
     public DefaultNetworkEvent(int netId, int[] transportTypes,
                 int prevNetId, boolean prevIPv4, boolean prevIPv6) {
         this.netId = netId;
@@ -106,8 +103,4 @@
             return new DefaultNetworkEvent[size];
         }
     };
-
-    public static void logEvent(
-            int netId, int[] transports, int prevNetId, boolean hadIPv4, boolean hadIPv6) {
-    }
 }
diff --git a/core/java/android/net/metrics/DhcpClientEvent.java b/core/java/android/net/metrics/DhcpClientEvent.java
index 4a9ff05..7e30ab5 100644
--- a/core/java/android/net/metrics/DhcpClientEvent.java
+++ b/core/java/android/net/metrics/DhcpClientEvent.java
@@ -16,7 +16,6 @@
 
 package android.net.metrics;
 
-import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 
@@ -24,7 +23,6 @@
  * An event recorded when a DhcpClient state machine transitions to a new state.
  * {@hide}
  */
-@SystemApi
 public final class DhcpClientEvent implements Parcelable {
 
     // Names for recording DhcpClient pseudo-state transitions.
@@ -37,7 +35,6 @@
     public final String msg;
     public final int durationMs;
 
-    /** {@hide} */
     public DhcpClientEvent(String ifName, String msg, int durationMs) {
         this.ifName = ifName;
         this.msg = msg;
@@ -77,7 +74,4 @@
             return new DhcpClientEvent[size];
         }
     };
-
-    public static void logStateEvent(String ifName, String state) {
-    }
 }
diff --git a/core/java/android/net/metrics/DhcpErrorEvent.java b/core/java/android/net/metrics/DhcpErrorEvent.java
index c3abcf7..f34ffdf 100644
--- a/core/java/android/net/metrics/DhcpErrorEvent.java
+++ b/core/java/android/net/metrics/DhcpErrorEvent.java
@@ -16,7 +16,6 @@
 
 package android.net.metrics;
 
-import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.util.SparseArray;
@@ -27,7 +26,6 @@
  * Event class used to record error events when parsing DHCP response packets.
  * {@hide}
  */
-@SystemApi
 public final class DhcpErrorEvent implements Parcelable {
     public static final int L2_ERROR   = 1;
     public static final int L3_ERROR   = 2;
@@ -50,12 +48,10 @@
     public static final int DHCP_INVALID_OPTION_LENGTH = makeErrorCode(DHCP_ERROR, 3);
     public static final int DHCP_NO_MSG_TYPE           = makeErrorCode(DHCP_ERROR, 4);
     public static final int DHCP_UNKNOWN_MSG_TYPE      = makeErrorCode(DHCP_ERROR, 5);
-    /** {@hide} */
     public static final int DHCP_NO_COOKIE             = makeErrorCode(DHCP_ERROR, 6);
 
     public static final int BUFFER_UNDERFLOW           = makeErrorCode(MISC_ERROR, 1);
     public static final int RECEIVE_ERROR              = makeErrorCode(MISC_ERROR, 2);
-    /** {@hide} */
     public static final int PARSING_ERROR              = makeErrorCode(MISC_ERROR, 3);
 
     public final String ifName;
@@ -66,7 +62,6 @@
     // byte 3: optional code
     public final int errorCode;
 
-    /** {@hide} */
     public DhcpErrorEvent(String ifName, int errorCode) {
         this.ifName = ifName;
         this.errorCode = errorCode;
@@ -99,12 +94,6 @@
         }
     };
 
-    public static void logParseError(String ifName, int errorCode) {
-    }
-
-    public static void logReceiveError(String ifName) {
-    }
-
     public static int errorCodeWithOption(int errorCode, int option) {
         return (0xFFFF0000 & errorCode) | (0xFF & option);
     }
diff --git a/core/java/android/net/metrics/DnsEvent.java b/core/java/android/net/metrics/DnsEvent.java
index 6176b2c..89ae1c2 100644
--- a/core/java/android/net/metrics/DnsEvent.java
+++ b/core/java/android/net/metrics/DnsEvent.java
@@ -16,7 +16,6 @@
 
 package android.net.metrics;
 
-import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 
@@ -24,7 +23,6 @@
  * A DNS event recorded by NetdEventListenerService.
  * {@hide}
  */
-@SystemApi
 final public class DnsEvent implements Parcelable {
     public final int netId;
 
@@ -38,7 +36,6 @@
     // queries.
     public final int[] latenciesMs;
 
-    /** {@hide} */
     public DnsEvent(int netId, byte[] eventTypes, byte[] returnCodes, int[] latenciesMs) {
         this.netId = netId;
         this.eventTypes = eventTypes;
@@ -82,8 +79,4 @@
             return new DnsEvent[size];
         }
     };
-
-    public static void logEvent(
-            int netId, byte[] eventTypes, byte[] returnCodes, int[] latenciesMs) {
-    }
 }
diff --git a/core/java/android/net/metrics/IpManagerEvent.java b/core/java/android/net/metrics/IpManagerEvent.java
index e0a026e..50dda7c 100644
--- a/core/java/android/net/metrics/IpManagerEvent.java
+++ b/core/java/android/net/metrics/IpManagerEvent.java
@@ -17,7 +17,6 @@
 package android.net.metrics;
 
 import android.annotation.IntDef;
-import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.util.SparseArray;
@@ -32,17 +31,15 @@
  * when a network disconnects.
  * {@hide}
  */
-@SystemApi
 public final class IpManagerEvent implements Parcelable {
 
-    public static final int PROVISIONING_OK    = 1;
-    public static final int PROVISIONING_FAIL  = 2;
-    public static final int COMPLETE_LIFECYCLE = 3;
-    /** @hide */ public static final int ERROR_STARTING_IPV4 = 4;
-    /** @hide */ public static final int ERROR_STARTING_IPV6 = 5;
-    /** @hide */ public static final int ERROR_STARTING_IPREACHABILITYMONITOR = 6;
+    public static final int PROVISIONING_OK                       = 1;
+    public static final int PROVISIONING_FAIL                     = 2;
+    public static final int COMPLETE_LIFECYCLE                    = 3;
+    public static final int ERROR_STARTING_IPV4                   = 4;
+    public static final int ERROR_STARTING_IPV6                   = 5;
+    public static final int ERROR_STARTING_IPREACHABILITYMONITOR  = 6;
 
-    /** {@hide} */
     @IntDef(value = {
             PROVISIONING_OK, PROVISIONING_FAIL, COMPLETE_LIFECYCLE,
             ERROR_STARTING_IPV4, ERROR_STARTING_IPV6, ERROR_STARTING_IPREACHABILITYMONITOR,
@@ -54,7 +51,6 @@
     public final @EventType int eventType;
     public final long durationMs;
 
-    /** {@hide} */
     public IpManagerEvent(String ifName, @EventType int eventType, long duration) {
         this.ifName = ifName;
         this.eventType = eventType;
@@ -90,9 +86,6 @@
         }
     };
 
-    public static void logEvent(int eventType, String ifName, long durationMs) {
-    }
-
     @Override
     public String toString() {
         return String.format("IpManagerEvent(%s, %s, %dms)",
diff --git a/core/java/android/net/metrics/IpReachabilityEvent.java b/core/java/android/net/metrics/IpReachabilityEvent.java
index ee09e22..d69e806 100644
--- a/core/java/android/net/metrics/IpReachabilityEvent.java
+++ b/core/java/android/net/metrics/IpReachabilityEvent.java
@@ -16,7 +16,6 @@
 
 package android.net.metrics;
 
-import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.util.SparseArray;
@@ -28,7 +27,6 @@
  * a neighbor probe result.
  * {@hide}
  */
-@SystemApi
 public final class IpReachabilityEvent implements Parcelable {
 
     // Event types.
@@ -38,9 +36,9 @@
     public static final int NUD_FAILED                = 2 << 8;
     /** Neighbor unreachable after a forced probe, IP provisioning is also lost. */
     public static final int PROVISIONING_LOST         = 3 << 8;
-    /** {@hide} Neighbor unreachable notification from kernel. */
+    /** Neighbor unreachable notification from kernel. */
     public static final int NUD_FAILED_ORGANIC        = 4 << 8;
-    /** {@hide} Neighbor unreachable notification from kernel, IP provisioning is also lost. */
+    /** Neighbor unreachable notification from kernel, IP provisioning is also lost. */
     public static final int PROVISIONING_LOST_ORGANIC = 5 << 8;
 
     public final String ifName;
@@ -51,7 +49,6 @@
     // byte 3: when byte 2 == PROBE, errno code from RTNetlink or IpReachabilityMonitor.
     public final int eventType;
 
-    /** {@hide} */
     public IpReachabilityEvent(String ifName, int eventType) {
         this.ifName = ifName;
         this.eventType = eventType;
@@ -84,18 +81,8 @@
         }
     };
 
-    public static void logProbeEvent(String ifName, int nlErrorCode) {
-    }
-
-    public static void logNudFailed(String ifName) {
-    }
-
-    public static void logProvisioningLost(String ifName) {
-    }
-
     /**
      * Returns the NUD failure event type code corresponding to the given conditions.
-     * {@hide}
      */
     public static int nudFailureEventType(boolean isFromProbe, boolean isProvisioningLost) {
         if (isFromProbe) {
diff --git a/core/java/android/net/metrics/NetworkEvent.java b/core/java/android/net/metrics/NetworkEvent.java
index 0667495..4df3bf0 100644
--- a/core/java/android/net/metrics/NetworkEvent.java
+++ b/core/java/android/net/metrics/NetworkEvent.java
@@ -17,7 +17,6 @@
 package android.net.metrics;
 
 import android.annotation.IntDef;
-import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.util.SparseArray;
@@ -30,7 +29,6 @@
 /**
  * {@hide}
  */
-@SystemApi
 public final class NetworkEvent implements Parcelable {
 
     public static final int NETWORK_CONNECTED            = 1;
@@ -41,16 +39,11 @@
     public static final int NETWORK_UNLINGER             = 6;
     public static final int NETWORK_DISCONNECTED         = 7;
 
-    /** {@hide} */
     public static final int NETWORK_FIRST_VALIDATION_SUCCESS      = 8;
-    /** {@hide} */
     public static final int NETWORK_REVALIDATION_SUCCESS          = 9;
-    /** {@hide} */
     public static final int NETWORK_FIRST_VALIDATION_PORTAL_FOUND = 10;
-    /** {@hide} */
     public static final int NETWORK_REVALIDATION_PORTAL_FOUND     = 11;
 
-    /** {@hide} */
     @IntDef(value = {
             NETWORK_CONNECTED,
             NETWORK_VALIDATED,
@@ -71,14 +64,12 @@
     public final @EventType int eventType;
     public final long durationMs;
 
-    /** {@hide} */
     public NetworkEvent(int netId, @EventType int eventType, long durationMs) {
         this.netId = netId;
         this.eventType = eventType;
         this.durationMs = durationMs;
     }
 
-    /** {@hide} */
     public NetworkEvent(int netId, @EventType int eventType) {
         this(netId, eventType, 0);
     }
@@ -112,15 +103,6 @@
         }
     };
 
-    public static void logEvent(int netId, int eventType) {
-    }
-
-    public static void logValidated(int netId, long durationMs) {
-    }
-
-    public static void logCaptivePortalFound(int netId, long durationMs) {
-    }
-
     @Override
     public String toString() {
         return String.format("NetworkEvent(%d, %s, %dms)",
diff --git a/core/java/android/net/metrics/RaEvent.java b/core/java/android/net/metrics/RaEvent.java
index 91bd023..3249f80 100644
--- a/core/java/android/net/metrics/RaEvent.java
+++ b/core/java/android/net/metrics/RaEvent.java
@@ -16,7 +16,6 @@
 
 package android.net.metrics;
 
-import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 
@@ -24,10 +23,8 @@
  * An event logged when the APF packet socket receives an RA packet.
  * {@hide}
  */
-@SystemApi
 public final class RaEvent implements Parcelable {
 
-    /** {@hide} */
     public static final long NO_LIFETIME = -1L;
 
     // Lifetime in seconds of options found in a single RA packet.
@@ -39,7 +36,6 @@
     public final long rdnssLifetime;
     public final long dnsslLifetime;
 
-    /** {@hide} */
     public RaEvent(long routerLifetime, long prefixValidLifetime, long prefixPreferredLifetime,
             long routeInfoLifetime, long rdnssLifetime, long dnsslLifetime) {
         this.routerLifetime = routerLifetime;
@@ -96,7 +92,6 @@
         }
     };
 
-    /** {@hide} */
     public static class Builder {
 
         long routerLifetime          = NO_LIFETIME;
diff --git a/core/java/android/net/metrics/ValidationProbeEvent.java b/core/java/android/net/metrics/ValidationProbeEvent.java
index a724ec1..70c6e84 100644
--- a/core/java/android/net/metrics/ValidationProbeEvent.java
+++ b/core/java/android/net/metrics/ValidationProbeEvent.java
@@ -17,7 +17,6 @@
 package android.net.metrics;
 
 import android.annotation.IntDef;
-import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.util.SparseArray;
@@ -31,14 +30,12 @@
  * An event recorded by NetworkMonitor when sending a probe for finding captive portals.
  * {@hide}
  */
-@SystemApi
 public final class ValidationProbeEvent implements Parcelable {
 
     public static final int PROBE_DNS       = 0;
     public static final int PROBE_HTTP      = 1;
     public static final int PROBE_HTTPS     = 2;
     public static final int PROBE_PAC       = 3;
-    /** {@hide} */
     public static final int PROBE_FALLBACK  = 4;
 
     public static final int DNS_FAILURE = 0;
@@ -47,7 +44,6 @@
     private static final int FIRST_VALIDATION  = 1 << 8;
     private static final int REVALIDATION      = 2 << 8;
 
-    /** {@hide} */
     @IntDef(value = {DNS_FAILURE, DNS_SUCCESS})
     @Retention(RetentionPolicy.SOURCE)
     public @interface ReturnCode {}
@@ -62,7 +58,6 @@
     public final int probeType;
     public final @ReturnCode int returnCode;
 
-    /** {@hide} */
     public ValidationProbeEvent(
             int netId, long durationMs, int probeType, @ReturnCode int returnCode) {
         this.netId = netId;
@@ -102,24 +97,18 @@
         }
     };
 
-    /** @hide */
     public static int makeProbeType(int probeType, boolean firstValidation) {
         return (probeType & 0xff) | (firstValidation ? FIRST_VALIDATION : REVALIDATION);
     }
 
-    /** @hide */
     public static String getProbeName(int probeType) {
         return Decoder.constants.get(probeType & 0xff, "PROBE_???");
     }
 
-    /** @hide */
     public static String getValidationStage(int probeType) {
         return Decoder.constants.get(probeType & 0xff00, "UNKNOWN");
     }
 
-    public static void logEvent(int netId, long durationMs, int probeType, int returnCode) {
-    }
-
     @Override
     public String toString() {
         return String.format("ValidationProbeEvent(%d, %s:%d %s, %dms)", netId,
diff --git a/core/java/android/os/FileUtils.java b/core/java/android/os/FileUtils.java
index 280fa2c..af05ee7 100644
--- a/core/java/android/os/FileUtils.java
+++ b/core/java/android/os/FileUtils.java
@@ -770,4 +770,17 @@
 
         return dir.mkdir() ? dir : null;
     }
+
+    /**
+     * Round the given size of a storage device to a nice round power-of-two
+     * value, such as 256MB or 32GB. This avoids showing weird values like
+     * "29.5GB" in UI.
+     */
+    public static long roundStorageSize(long size) {
+        long res = 1;
+        while (res < size) {
+            res <<= 1;
+        }
+        return res;
+    }
 }
diff --git a/core/java/android/os/storage/StorageManager.java b/core/java/android/os/storage/StorageManager.java
index e070c6e..a1f8dfb 100644
--- a/core/java/android/os/storage/StorageManager.java
+++ b/core/java/android/os/storage/StorageManager.java
@@ -1677,8 +1677,8 @@
                 "Well this is embarassing; we can't allocate " + bytes + " for " + file);
     }
 
-    private static final String XATTR_ATOMIC = "user.atomic";
-    private static final String XATTR_TOMBSTONE = "user.tombstone";
+    private static final String XATTR_CACHE_ATOMIC = "user.cache_atomic";
+    private static final String XATTR_CACHE_TOMBSTONE = "user.cache_tombstone";
 
     /** {@hide} */
     private static void setCacheBehavior(File path, String name, boolean enabled)
@@ -1736,7 +1736,7 @@
      * to all contained files and directories.
      */
     public void setCacheBehaviorAtomic(File path, boolean atomic) throws IOException {
-        setCacheBehavior(path, XATTR_ATOMIC, atomic);
+        setCacheBehavior(path, XATTR_CACHE_ATOMIC, atomic);
     }
 
     /**
@@ -1744,7 +1744,7 @@
      * {@link #setCacheBehaviorAtomic(File, boolean)}.
      */
     public boolean isCacheBehaviorAtomic(File path) throws IOException {
-        return isCacheBehavior(path, XATTR_ATOMIC);
+        return isCacheBehavior(path, XATTR_CACHE_ATOMIC);
     }
 
     /**
@@ -1764,7 +1764,7 @@
      * </p>
      */
     public void setCacheBehaviorTombstone(File path, boolean tombstone) throws IOException {
-        setCacheBehavior(path, XATTR_TOMBSTONE, tombstone);
+        setCacheBehavior(path, XATTR_CACHE_TOMBSTONE, tombstone);
     }
 
     /**
@@ -1772,7 +1772,7 @@
      * {@link #setCacheBehaviorTombstone(File, boolean)}.
      */
     public boolean isCacheBehaviorTombstone(File path) throws IOException {
-        return isCacheBehavior(path, XATTR_TOMBSTONE);
+        return isCacheBehavior(path, XATTR_CACHE_TOMBSTONE);
     }
 
     private final Object mFuseAppLoopLock = new Object();
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 6c319ab..40de928 100755
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -4635,7 +4635,7 @@
                 return setLocationModeForUser(resolver, Integer.parseInt(value), userHandle);
             }
             if (MOVED_TO_GLOBAL.contains(name)) {
-                Log.w(TAG, "Setting " + name + " has moved from android.provider.Settings.System"
+                Log.w(TAG, "Setting " + name + " has moved from android.provider.Settings.Secure"
                         + " to android.provider.Settings.Global");
                 return Global.putStringForUser(resolver, name, value,
                         tag, makeDefault, userHandle);
@@ -8258,6 +8258,15 @@
         public static final String CURATE_SAVED_OPEN_NETWORKS = "curate_saved_open_networks";
 
         /**
+         * The package name of the application that connect and secures high quality open wifi
+         * networks automatically.
+         *
+         * Type: string package name or null if the feature is either not provided or disabled.
+         * @hide
+         */
+        public static final String USE_OPEN_WIFI_PACKAGE = "use_open_wifi_package";
+
+        /**
          * The number of milliseconds the {@link com.android.server.NetworkScoreService}
          * will give a recommendation request to complete before returning a default response.
          *
@@ -9625,16 +9634,6 @@
         public static final String RETAIL_DEMO_MODE_CONSTANTS = "retail_demo_mode_constants";
 
         /**
-         * When blocked for the network policy rules to get updated, the maximum time that the
-         * {@link ActivityThread} have to wait before unblocking.
-         *
-         * Type: long
-         *
-         * @hide
-         */
-        public static final String WAIT_FOR_NETWORK_TIMEOUT_MS = "wait_for_network_timeout_ms";
-
-        /**
          * The reason for the settings database being downgraded. This is only for
          * troubleshooting purposes and its value should not be interpreted in any way.
          *
@@ -9689,6 +9688,7 @@
             CURATE_SAVED_OPEN_NETWORKS,
             WIFI_WAKEUP_ENABLED,
             WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
+            USE_OPEN_WIFI_PACKAGE,
             WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED,
             EMERGENCY_TONE,
             CALL_AUTO_RETRY,
@@ -10217,6 +10217,13 @@
          * @hide
          */
         public static final String ENABLE_DISKSTATS_LOGGING = "enable_diskstats_logging";
+
+        /**
+         * Whether the cache quota calculation task is enabled/disabled.
+         * @hide
+         */
+        public static final String ENABLE_CACHE_QUOTA_CALCULATION =
+                "enable_cache_quota_calculation";
     }
 
     /**
diff --git a/core/java/android/view/Display.java b/core/java/android/view/Display.java
index 83b6a52..7ec7ba7 100644
--- a/core/java/android/view/Display.java
+++ b/core/java/android/view/Display.java
@@ -21,6 +21,7 @@
 import android.annotation.IntDef;
 import android.annotation.RequiresPermission;
 import android.content.res.CompatibilityInfo;
+import android.content.res.Resources;
 import android.graphics.PixelFormat;
 import android.graphics.Point;
 import android.graphics.Rect;
@@ -71,7 +72,8 @@
     private final String mAddress;
     private final int mOwnerUid;
     private final String mOwnerPackageName;
-    private final DisplayAdjustments mDisplayAdjustments;
+    private final Resources mResources;
+    private DisplayAdjustments mDisplayAdjustments;
 
     private DisplayInfo mDisplayInfo; // never null
     private boolean mIsValid;
@@ -355,19 +357,39 @@
 
     /**
      * Internal method to create a display.
+     * The display created with this method will have a static {@link DisplayAdjustments} applied.
      * Applications should use {@link android.view.WindowManager#getDefaultDisplay()}
      * or {@link android.hardware.display.DisplayManager#getDisplay}
      * to get a display object.
      *
      * @hide
      */
-    public Display(DisplayManagerGlobal global,
-            int displayId, DisplayInfo displayInfo /*not null*/,
+    public Display(DisplayManagerGlobal global, int displayId, /*@NotNull*/ DisplayInfo displayInfo,
             DisplayAdjustments daj) {
+        this(global, displayId, displayInfo, daj, null /*res*/);
+    }
+
+    /**
+     * Internal method to create a display.
+     * The display created with this method will be adjusted based on the adjustments in the
+     * supplied {@link Resources}.
+     *
+     * @hide
+     */
+    public Display(DisplayManagerGlobal global, int displayId, /*@NotNull*/ DisplayInfo displayInfo,
+            Resources res) {
+        this(global, displayId, displayInfo, null /*daj*/, res);
+    }
+
+    private Display(DisplayManagerGlobal global, int displayId,
+            /*@NotNull*/ DisplayInfo displayInfo, DisplayAdjustments daj, Resources res) {
         mGlobal = global;
         mDisplayId = displayId;
         mDisplayInfo = displayInfo;
-        mDisplayAdjustments = new DisplayAdjustments(daj);
+        mResources = res;
+        mDisplayAdjustments = mResources != null
+            ? new DisplayAdjustments(mResources.getConfiguration())
+            : daj != null ? new DisplayAdjustments(daj) : null;
         mIsValid = true;
 
         // Cache properties that cannot change as long as the display is valid.
@@ -512,6 +534,13 @@
      * @hide
      */
     public DisplayAdjustments getDisplayAdjustments() {
+        if (mResources != null) {
+            final DisplayAdjustments currentAdjustements = mResources.getDisplayAdjustments();
+            if (!mDisplayAdjustments.equals(currentAdjustements)) {
+                mDisplayAdjustments = new DisplayAdjustments(currentAdjustements);
+            }
+        }
+
         return mDisplayAdjustments;
     }
 
@@ -562,7 +591,7 @@
     public void getSize(Point outSize) {
         synchronized (this) {
             updateDisplayInfoLocked();
-            mDisplayInfo.getAppMetrics(mTempMetrics, mDisplayAdjustments);
+            mDisplayInfo.getAppMetrics(mTempMetrics, getDisplayAdjustments());
             outSize.x = mTempMetrics.widthPixels;
             outSize.y = mTempMetrics.heightPixels;
         }
@@ -577,7 +606,7 @@
     public void getRectSize(Rect outSize) {
         synchronized (this) {
             updateDisplayInfoLocked();
-            mDisplayInfo.getAppMetrics(mTempMetrics, mDisplayAdjustments);
+            mDisplayInfo.getAppMetrics(mTempMetrics, getDisplayAdjustments());
             outSize.set(0, 0, mTempMetrics.widthPixels, mTempMetrics.heightPixels);
         }
     }
@@ -908,7 +937,7 @@
     public void getMetrics(DisplayMetrics outMetrics) {
         synchronized (this) {
             updateDisplayInfoLocked();
-            mDisplayInfo.getAppMetrics(outMetrics, mDisplayAdjustments);
+            mDisplayInfo.getAppMetrics(outMetrics, getDisplayAdjustments());
         }
     }
 
@@ -1017,7 +1046,7 @@
         long now = SystemClock.uptimeMillis();
         if (now > mLastCachedAppSizeUpdate + CACHED_APP_SIZE_DURATION_MILLIS) {
             updateDisplayInfoLocked();
-            mDisplayInfo.getAppMetrics(mTempMetrics, mDisplayAdjustments);
+            mDisplayInfo.getAppMetrics(mTempMetrics, getDisplayAdjustments());
             mCachedAppWidthCompat = mTempMetrics.widthPixels;
             mCachedAppHeightCompat = mTempMetrics.heightPixels;
             mLastCachedAppSizeUpdate = now;
@@ -1029,7 +1058,7 @@
     public String toString() {
         synchronized (this) {
             updateDisplayInfoLocked();
-            mDisplayInfo.getAppMetrics(mTempMetrics, mDisplayAdjustments);
+            mDisplayInfo.getAppMetrics(mTempMetrics, getDisplayAdjustments());
             return "Display id " + mDisplayId + ": " + mDisplayInfo
                     + ", " + mTempMetrics + ", isValid=" + mIsValid;
         }
diff --git a/core/java/android/view/FrameMetrics.java b/core/java/android/view/FrameMetrics.java
index 92f0e8f..358a2d1 100644
--- a/core/java/android/view/FrameMetrics.java
+++ b/core/java/android/view/FrameMetrics.java
@@ -132,6 +132,26 @@
      */
     public static final int FIRST_DRAW_FRAME = 9;
 
+    /**
+     * Metric identifier for the timestamp of the intended vsync for this frame.
+     * <p>
+     * The intended start point for the frame. If this value is different from
+     * {@link #VSYNC_TIMESTAMP}, there was work occurring on the UI thread that
+     * prevented it from responding to the vsync signal in a timely fashion.
+     * </p>
+     */
+    public static final int INTENDED_VSYNC_TIMESTAMP = 10;
+
+    /**
+     * Metric identifier for the timestamp of the actual vsync for this frame.
+     * <p>
+     * The time value that was used in all the vsync listeners and drawing for
+     * the frame (Choreographer frame callbacks, animations,
+     * {@link View#getDrawingTime()}, etc…)
+     * </p>
+     */
+    public static final int VSYNC_TIMESTAMP = 11;
+
     private static final int FRAME_INFO_FLAG_FIRST_DRAW = 1 << 0;
 
     /**
@@ -151,6 +171,8 @@
             SWAP_BUFFERS_DURATION,
             TOTAL_DURATION,
             FIRST_DRAW_FRAME,
+            INTENDED_VSYNC_TIMESTAMP,
+            VSYNC_TIMESTAMP,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface Metric {}
@@ -261,7 +283,7 @@
      * @return the value of the metric or -1 if it is not available.
      */
     public long getMetric(@Metric int id) {
-        if (id < UNKNOWN_DELAY_DURATION || id > FIRST_DRAW_FRAME) {
+        if (id < UNKNOWN_DELAY_DURATION || id > VSYNC_TIMESTAMP) {
             return -1;
         }
 
@@ -271,6 +293,10 @@
 
         if (id == FIRST_DRAW_FRAME) {
             return (mTimingData[Index.FLAGS] & FRAME_INFO_FLAG_FIRST_DRAW) != 0 ? 1 : 0;
+        } else if (id == INTENDED_VSYNC_TIMESTAMP) {
+            return mTimingData[Index.INTENDED_VSYNC];
+        } else if (id == VSYNC_TIMESTAMP) {
+            return mTimingData[Index.VSYNC];
         }
 
         int durationsIdx = 2 * id;
diff --git a/core/java/android/view/SurfaceControl.java b/core/java/android/view/SurfaceControl.java
index cf8da17..b718696 100644
--- a/core/java/android/view/SurfaceControl.java
+++ b/core/java/android/view/SurfaceControl.java
@@ -508,9 +508,9 @@
         nativeSetAlpha(mNativeObject, alpha);
     }
 
-    public void setMatrix(float dsdx, float dtdx, float dsdy, float dtdy) {
+    public void setMatrix(float dsdx, float dtdx, float dtdy, float dsdy) {
         checkNotReleased();
-        nativeSetMatrix(mNativeObject, dsdx, dtdx, dsdy, dtdy);
+        nativeSetMatrix(mNativeObject, dsdx, dtdx, dtdy, dsdy);
     }
 
     public void setWindowCrop(Rect crop) {
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index aa85a98..66c394f 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -6984,8 +6984,12 @@
      * Called when assist structure is being retrieved from a view as part of an auto-fill request.
      *
      * <p>This method already provides most of what's needed for auto-fill, but should be overridden
-     * when the view contents does not include PII (Personally Identifiable Information) (so it
-     * can call {@link ViewStructure#setSanitized(boolean) ViewStructure#setSanitized(true)}).
+     * <ol>
+     * <li>The view contents does not include PII (Personally Identifiable Information), so it
+     * can call {@link ViewStructure#setSanitized(boolean)} passing {@code true}.
+     * <li>It must set fields such {@link ViewStructure#setText(CharSequence)},
+     * {@link ViewStructure#setAutoFillOptions(String[])}, or {@link ViewStructure#setUrl(String)}.
+     * </ol>
      *
      * @param structure Fill in with structured view data. The default implementation
      * fills in all data that can be inferred from the view itself.
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index c81e938..595e7a1 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -1047,8 +1047,8 @@
 
         // Get new instance of display based on current display adjustments. It may be updated later
         // if moving between the displays also involved a configuration change.
-        final DisplayAdjustments displayAdjustments = mView.getResources().getDisplayAdjustments();
-        mDisplay = ResourcesManager.getInstance().getAdjustedDisplay(displayId, displayAdjustments);
+        mDisplay = ResourcesManager.getInstance().getAdjustedDisplay(displayId,
+            mView.getResources());
         mAttachInfo.mDisplayState = mDisplay.getState();
         // Internal state updated, now notify the view hierarchy.
         mView.dispatchMovedToDisplay(mDisplay);
@@ -3384,7 +3384,7 @@
             if (force || mLastConfiguration.diff(config) != 0) {
                 // Update the display with new DisplayAdjustments.
                 mDisplay = ResourcesManager.getInstance().getAdjustedDisplay(
-                        mDisplay.getDisplayId(), localResources.getDisplayAdjustments());
+                        mDisplay.getDisplayId(), localResources);
 
                 final int lastLayoutDirection = mLastConfiguration.getLayoutDirection();
                 final int currentLayoutDirection = config.getLayoutDirection();
diff --git a/core/java/android/view/ViewStructure.java b/core/java/android/view/ViewStructure.java
index bc2725f..84c2c84 100644
--- a/core/java/android/view/ViewStructure.java
+++ b/core/java/android/view/ViewStructure.java
@@ -307,6 +307,15 @@
     public abstract void setAutoFillValue(AutoFillValue value);
 
     /**
+     * Sets the options that can be used to auto-fill this node.
+     *
+     * <p>Typically used by nodes whose {@link AutoFillType} is a list to indicate the meaning of
+     * each possible value in the list.
+     */
+    // TODO(b/33197203, b/33802548): add CTS/unit test
+    public abstract void setAutoFillOptions(String[] options);
+
+    /**
      * Marks this node as sanitized so its content are sent on {@link
      * android.service.autofill.AutoFillService#onFillRequest(android.app.assist.AssistStructure,
      * Bundle, android.os.CancellationSignal, android.service.autofill.FillCallback)}.
diff --git a/core/java/android/view/autofill/AutoFillManager.java b/core/java/android/view/autofill/AutoFillManager.java
index 2168444..e82021e 100644
--- a/core/java/android/view/autofill/AutoFillManager.java
+++ b/core/java/android/view/autofill/AutoFillManager.java
@@ -26,7 +26,6 @@
 import android.os.IBinder;
 import android.os.Parcelable;
 import android.os.RemoteException;
-import android.util.ArrayMap;
 import android.util.Log;
 import android.view.View;
 
@@ -70,13 +69,6 @@
     /** @hide */ public static final int FLAG_FOCUS_LOST = 0x4;
     /** @hide */ public static final int FLAG_VALUE_CHANGED = 0x8;
 
-    // These are activities that may have auto-fill UI which are keyed off their tokens.
-    // This is done instead of the activity setting the client in the auto-fill manager
-    // to avoid unnecessary instantiation of the manager and do this only if there is an
-    // auto-fillable focused. This has only the cost of loading the class vs creating an
-    // auto-fill manager for every activity even one that cannot be filled.
-    private static final ArrayMap<IBinder, AutoFillClient> sPendingClients = new ArrayMap<>();
-
     private final Rect mTempRect = new Rect();
 
     private final IAutoFillManager mService;
@@ -84,8 +76,6 @@
 
     private Context mContext;
 
-    private AutoFillClient mClient;
-
     private boolean mHasSession;
     private boolean mEnabled;
 
@@ -106,6 +96,11 @@
          * @param fillInIntent The authentication fill-in intent.
          */
         void authenticate(IntentSender intent, Intent fillInIntent);
+
+        /**
+         * Tells the client this manager has state to be reset.
+         */
+        void resetableStateAvailable();
     }
 
     /**
@@ -137,7 +132,7 @@
         if (!mHasSession) {
             if (gainFocus) {
                 // Starts new session.
-                startSession(id, bounds, value);
+                startSession(id, view.getWindowToken(), bounds, value);
             }
         } else {
             // Update focus on existing session.
@@ -165,7 +160,7 @@
         if (!mHasSession) {
             if (gainFocus) {
                 // Starts new session.
-                startSession(id, bounds, null);
+                startSession(id, parent.getWindowToken(), bounds, null);
             }
         } else {
             // Update focus on existing session.
@@ -219,25 +214,11 @@
         finishSession();
     }
 
-    /** @hide */
-    public static void addClient(IBinder token, AutoFillClient client) {
-        sPendingClients.put(token, client);
-    }
-
-    /** @hide */
-    public static boolean isClientActive(IBinder token) {
-        return !sPendingClients.containsKey(token);
-    }
-
-    private void activateClient() {
-        mClient = sPendingClients.remove(mContext.getActivityToken());
-    }
-
     private AutoFillClient getClient() {
-        if (mClient == null) {
-            return sPendingClients.get(mContext.getActivityToken());
+        if (mContext instanceof AutoFillClient) {
+            return (AutoFillClient) mContext;
         }
-        return mClient;
+        return null;
     }
 
     /** @hide */
@@ -271,15 +252,19 @@
         return new AutoFillId(parent.getAccessibilityViewId(), childId);
     }
 
-    private void startSession(AutoFillId id, Rect bounds, AutoFillValue value) {
+    private void startSession(AutoFillId id, IBinder windowToken,
+            Rect bounds, AutoFillValue value) {
         if (DEBUG) {
             Log.v(TAG, "startSession(): id=" + id + ", bounds=" + bounds + ", value=" + value);
         }
         try {
-            mService.startSession(mContext.getActivityToken(), mServiceClient.asBinder(),
-                    id, bounds, value, mContext.getUserId());
+            mService.startSession(mContext.getActivityToken(), windowToken,
+                    mServiceClient.asBinder(), id, bounds, value, mContext.getUserId());
+            AutoFillClient client = getClient();
+            if (client != null) {
+                client.resetableStateAvailable();
+            }
             mHasSession = true;
-            activateClient();
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
diff --git a/core/java/android/view/autofill/AutoFillType.java b/core/java/android/view/autofill/AutoFillType.java
index 017f7f8..5d85bfd 100644
--- a/core/java/android/view/autofill/AutoFillType.java
+++ b/core/java/android/view/autofill/AutoFillType.java
@@ -44,8 +44,6 @@
 
     private static final int TYPE_TEXT = 1;
     private static final int TYPE_TOGGLE = 2;
-    // TODO(b/33197203): make sure it works with Spinners and/or add a new type for them
-    // (since they're often used for credit card selection)
     private static final int TYPE_LIST = 3;
 
     // TODO(b/33197203): add others, like date picker? That would be trick, because they're set as:
diff --git a/core/java/android/view/autofill/IAutoFillManager.aidl b/core/java/android/view/autofill/IAutoFillManager.aidl
index 0433a8f..d054e97 100644
--- a/core/java/android/view/autofill/IAutoFillManager.aidl
+++ b/core/java/android/view/autofill/IAutoFillManager.aidl
@@ -30,7 +30,7 @@
  */
 interface IAutoFillManager {
     boolean addClient(in IAutoFillManagerClient client, int userId);
-    oneway void startSession(in IBinder activityToken, in IBinder appCallback,
+    oneway void startSession(in IBinder activityToken, IBinder windowToken, in IBinder appCallback,
             in AutoFillId autoFillId, in Rect bounds, in AutoFillValue value, int userId);
     oneway void updateSession(in IBinder activityToken, in AutoFillId id, in Rect bounds,
             in AutoFillValue value, int flags, int userId);
diff --git a/core/java/android/webkit/WebViewZygote.java b/core/java/android/webkit/WebViewZygote.java
index 2d6f443..f9d7332 100644
--- a/core/java/android/webkit/WebViewZygote.java
+++ b/core/java/android/webkit/WebViewZygote.java
@@ -176,7 +176,7 @@
             // paths and pass them to the zygote as strings.
             final List<String> zipPaths = new ArrayList<>(10);
             final List<String> libPaths = new ArrayList<>(10);
-            LoadedApk.makePaths(null, sPackage.applicationInfo, zipPaths, libPaths);
+            LoadedApk.makePaths(null, false, sPackage.applicationInfo, zipPaths, libPaths);
             final String librarySearchPath = TextUtils.join(File.pathSeparator, libPaths);
             final String zip = (zipPaths.size() == 1) ? zipPaths.get(0) :
                     TextUtils.join(File.pathSeparator, zipPaths);
diff --git a/core/java/android/widget/AdapterView.java b/core/java/android/widget/AdapterView.java
index 2cfefba..0b3cff1 100644
--- a/core/java/android/widget/AdapterView.java
+++ b/core/java/android/widget/AdapterView.java
@@ -34,6 +34,7 @@
 import android.view.accessibility.AccessibilityEvent;
 import android.view.accessibility.AccessibilityManager;
 import android.view.accessibility.AccessibilityNodeInfo;
+import android.view.autofill.AutoFillManager;
 
 /**
  * An AdapterView is a view whose children are determined by an {@link Adapter}.
@@ -914,6 +915,11 @@
                 dispatchOnItemSelected();
             }
         }
+        // Always notify AutoFillManager - it will return right away if auto-fill is disabled.
+        final AutoFillManager afm = mContext.getSystemService(AutoFillManager.class);
+        if (afm != null) {
+            afm.valueChanged(this);
+        }
     }
 
     private void dispatchOnItemSelected() {
diff --git a/core/java/android/widget/CompoundButton.java b/core/java/android/widget/CompoundButton.java
index f2c2af5..887c59a 100644
--- a/core/java/android/widget/CompoundButton.java
+++ b/core/java/android/widget/CompoundButton.java
@@ -32,6 +32,7 @@
 import android.view.SoundEffectConstants;
 import android.view.ViewDebug;
 import android.view.ViewHierarchyEncoder;
+import android.view.ViewStructure;
 import android.view.accessibility.AccessibilityEvent;
 import android.view.accessibility.AccessibilityNodeInfo;
 import android.view.autofill.AutoFillManager;
@@ -68,6 +69,10 @@
     private OnCheckedChangeListener mOnCheckedChangeListener;
     private OnCheckedChangeListener mOnCheckedChangeWidgetListener;
 
+    // Indicates whether the toggle state was set from resources or dynamically, so it can be used
+    // to sanitize auto-fill requests.
+    private boolean mCheckedFromResource = false;
+
     private static final int[] CHECKED_STATE_SET = {
         R.attr.state_checked
     };
@@ -109,6 +114,7 @@
         final boolean checked = a.getBoolean(
                 com.android.internal.R.styleable.CompoundButton_checked, false);
         setChecked(checked);
+        mCheckedFromResource = true;
 
         a.recycle();
 
@@ -148,6 +154,7 @@
     @Override
     public void setChecked(boolean checked) {
         if (mChecked != checked) {
+            mCheckedFromResource = false;
             mChecked = checked;
             refreshDrawableState();
             notifyViewAccessibilityStateChangedIfNeeded(
@@ -569,6 +576,13 @@
     // TODO(b/33197203): add unit/CTS tests for auto-fill methods (and make sure they handle enable)
 
     @Override
+    public void onProvideAutoFillStructure(ViewStructure structure, int flags) {
+        super.onProvideAutoFillStructure(structure, flags);
+
+        structure.setSanitized(mCheckedFromResource);
+    }
+
+    @Override
     public void autoFill(AutoFillValue value) {
         if (!isEnabled()) return;
 
diff --git a/core/java/android/widget/RadioGroup.java b/core/java/android/widget/RadioGroup.java
index 76b3813..bba3a11 100644
--- a/core/java/android/widget/RadioGroup.java
+++ b/core/java/android/widget/RadioGroup.java
@@ -24,6 +24,7 @@
 import android.util.Log;
 import android.view.View;
 import android.view.ViewGroup;
+import android.view.ViewStructure;
 import android.view.autofill.AutoFillManager;
 import android.view.autofill.AutoFillType;
 import android.view.autofill.AutoFillValue;
@@ -66,6 +67,10 @@
     private OnCheckedChangeListener mOnCheckedChangeListener;
     private PassThroughHierarchyChangeListener mPassThroughListener;
 
+    // Indicates whether the child was set from resources or dynamically, so it can be used
+    // to sanitize auto-fill requests.
+    private int mInitialCheckedId = View.NO_ID;
+
     /**
      * {@inheritDoc}
      */
@@ -89,8 +94,8 @@
         int value = attributes.getResourceId(R.styleable.RadioGroup_checkedButton, View.NO_ID);
         if (value != View.NO_ID) {
             mCheckedId = value;
+            mInitialCheckedId = value;
         }
-
         final int index = attributes.getInt(com.android.internal.R.styleable.RadioGroup_orientation, VERTICAL);
         setOrientation(index);
 
@@ -411,6 +416,12 @@
     // TODO(b/33197203): add unit/CTS tests for auto-fill methods (and make sure they handle enable)
 
     @Override
+    public void onProvideAutoFillStructure(ViewStructure structure, int flags) {
+        super.onProvideAutoFillStructure(structure, flags);
+        structure.setSanitized(mCheckedId == mInitialCheckedId);
+    }
+
+    @Override
     public void autoFill(AutoFillValue value) {
         if (!isEnabled()) return;
 
@@ -430,6 +441,15 @@
 
     @Override
     public AutoFillValue getAutoFillValue() {
-        return isEnabled() ? AutoFillValue.forList(getCheckedRadioButtonId()) : null;
+        if (!isEnabled()) return null;
+
+        final int count = getChildCount();
+        for (int i = 0; i < count; i++) {
+            final View child = getChildAt(i);
+            if (child.getId() == mCheckedId) {
+                return AutoFillValue.forList(i);
+            }
+        }
+        return null;
     }
 }
diff --git a/core/java/android/widget/Spinner.java b/core/java/android/widget/Spinner.java
index 28cc693..50c016b 100644
--- a/core/java/android/widget/Spinner.java
+++ b/core/java/android/widget/Spinner.java
@@ -41,9 +41,12 @@
 import android.view.PointerIcon;
 import android.view.View;
 import android.view.ViewGroup;
+import android.view.ViewStructure;
 import android.view.ViewTreeObserver;
 import android.view.ViewTreeObserver.OnGlobalLayoutListener;
 import android.view.accessibility.AccessibilityNodeInfo;
+import android.view.autofill.AutoFillType;
+import android.view.autofill.AutoFillValue;
 import android.widget.PopupWindow.OnDismissListener;
 
 import com.android.internal.R;
@@ -784,6 +787,7 @@
         return handled;
     }
 
+    @Override
     public void onClick(DialogInterface dialog, int which) {
         setSelection(which);
         dialog.dismiss();
@@ -912,6 +916,42 @@
         return super.onResolvePointerIcon(event, pointerIndex);
     }
 
+    // TODO(b/33197203): add unit/CTS tests for auto-fill methods (and make sure they handle enable)
+
+    @Override
+    public void onProvideAutoFillStructure(ViewStructure structure, int flags) {
+        super.onProvideAutoFillStructure(structure, flags);
+        // TODO(b/33197203): implement sanitization so initial value is only sanitized when coming
+        // from resources.
+
+        final int count = getAdapter().getCount();
+        if (count > 0) {
+            final String[] options = new String[count];
+            for (int i = 0; i < count; i++) {
+                options[i] = getAdapter().getItem(i).toString();
+            }
+            structure.setAutoFillOptions(options);
+        }
+    }
+
+    @Override
+    public void autoFill(AutoFillValue value) {
+        if (!isEnabled()) return;
+
+        final int position = value.getListValue();
+        setSelection(position);
+    }
+
+    @Override
+    public AutoFillType getAutoFillType() {
+        return AutoFillType.forList();
+    }
+
+    @Override
+    public AutoFillValue getAutoFillValue() {
+        return isEnabled() ? AutoFillValue.forList(getSelectedItemPosition()) : null;
+    }
+
     static class SavedState extends AbsSpinner.SavedState {
         boolean showDropdown;
 
diff --git a/core/java/android/widget/TextInputTimePickerView.java b/core/java/android/widget/TextInputTimePickerView.java
index ef91576..0183343 100644
--- a/core/java/android/widget/TextInputTimePickerView.java
+++ b/core/java/android/widget/TextInputTimePickerView.java
@@ -177,15 +177,15 @@
 
         mAmPmSpinner.setVisibility(is24Hour ? View.INVISIBLE : View.VISIBLE);
 
-        mHourEditText.setText(String.format(format, localizedHour));
-        mMinuteEditText.setText(String.format(format, minute));
-
         if (amOrPm == AM) {
             mAmPmSpinner.setSelection(0);
         } else {
             mAmPmSpinner.setSelection(1);
         }
 
+        mHourEditText.setText(String.format(format, localizedHour));
+        mMinuteEditText.setText(String.format(format, minute));
+
         if (mErrorShowing) {
             validateInput();
         }
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 9e911632..5e6e0f9 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -727,7 +727,7 @@
     private boolean mHasPresetAutoSizeValues = false;
 
     // Indicates whether the text was set from resources or dynamically, so it can be used to
-    // sanitize auto-fill request.
+    // sanitize auto-fill requests.
     private boolean mTextFromResource = false;
 
     /**
@@ -5219,6 +5219,9 @@
 
         if (needEditableForNotification) {
             sendAfterTextChanged((Editable) text);
+        } else {
+            // Always notify AutoFillManager - it will return right away if auto-fill is disabled.
+            notifyAutoFillManagerAfterTextChanged();
         }
 
         // SelectionModifierCursorController depends on textCanBeSelected, which depends on text
@@ -9111,15 +9114,19 @@
         }
 
         // Always notify AutoFillManager - it will return right away if auto-fill is disabled.
+        notifyAutoFillManagerAfterTextChanged();
+
+        hideErrorIfUnchanged();
+    }
+
+    private void notifyAutoFillManagerAfterTextChanged() {
         final AutoFillManager afm = mContext.getSystemService(AutoFillManager.class);
         if (afm != null) {
             if (DEBUG_AUTOFILL) {
-                Log.v(LOG_TAG, "sendAfterTextChanged(): notify AFM for text=" + text);
+                Log.v(LOG_TAG, "sendAfterTextChanged(): notify AFM for text=" + mText);
             }
             afm.valueChanged(TextView.this);
         }
-
-        hideErrorIfUnchanged();
     }
 
     void updateAfterEdit() {
diff --git a/core/java/android/widget/VideoView.java b/core/java/android/widget/VideoView.java
index b973324..7b2efea 100644
--- a/core/java/android/widget/VideoView.java
+++ b/core/java/android/widget/VideoView.java
@@ -16,11 +16,13 @@
 
 package android.widget;
 
+import android.annotation.NonNull;
 import android.app.AlertDialog;
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.res.Resources;
 import android.graphics.Canvas;
+import android.media.AudioAttributes;
 import android.media.AudioManager;
 import android.media.Cea708CaptionRenderer;
 import android.media.ClosedCaptionRenderer;
@@ -67,6 +69,14 @@
  * {@link android.app.Activity#onRestoreInstanceState}.<p>
  * Also note that the audio session id (from {@link #getAudioSessionId}) may
  * change from its previously returned value when the VideoView is restored.
+ * <p>
+ * By default, VideoView requests audio focus with {@link AudioManager#AUDIOFOCUS_GAIN}. Use
+ * {@link #setAudioFocusRequest(int)} to change this behavior.
+ * <p>
+ * The default {@link AudioAttributes} used during playback have a usage of
+ * {@link AudioAttributes#USAGE_MEDIA} and a content type of
+ * {@link AudioAttributes#CONTENT_TYPE_MOVIE}, use {@link #setAudioAttributes(AudioAttributes)} to
+ * modify them.
  */
 public class VideoView extends SurfaceView
         implements MediaPlayerControl, SubtitleController.Anchor {
@@ -113,6 +123,9 @@
     private boolean mCanPause;
     private boolean mCanSeekBack;
     private boolean mCanSeekForward;
+    private AudioManager mAudioManager;
+    private int mAudioFocusType = AudioManager.AUDIOFOCUS_GAIN; // legacy focus gain
+    private AudioAttributes mAudioAttributes;
 
     /** Subtitle rendering widget overlaid on top of the video. */
     private RenderingWidget mSubtitleWidget;
@@ -138,6 +151,10 @@
         mVideoWidth = 0;
         mVideoHeight = 0;
 
+        mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
+        mAudioAttributes = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
+                .setContentType(AudioAttributes.CONTENT_TYPE_MOVIE).build();
+
         getHolder().addCallback(mSHCallback);
         getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
 
@@ -260,6 +277,41 @@
     }
 
     /**
+     * Sets which type of audio focus will be requested during the playback, or configures playback
+     * to not request audio focus. Valid values for focus requests are
+     * {@link AudioManager#AUDIOFOCUS_GAIN}, {@link AudioManager#AUDIOFOCUS_GAIN_TRANSIENT},
+     * {@link AudioManager#AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK}, and
+     * {@link AudioManager#AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE}. Or use
+     * {@link AudioManager#AUDIOFOCUS_NONE} to express that audio focus should not be
+     * requested when playback starts. You can for instance use this when playing a silent animation
+     * through this class, and you don't want to affect other audio applications playing in the
+     * background.
+     * @param focusGain the type of audio focus gain that will be requested, or
+     *    {@link AudioManager#AUDIOFOCUS_NONE} to disable the use audio focus during playback.
+     */
+    public void setAudioFocusRequest(int focusGain) {
+        if (focusGain != AudioManager.AUDIOFOCUS_NONE
+                && focusGain != AudioManager.AUDIOFOCUS_GAIN
+                && focusGain != AudioManager.AUDIOFOCUS_GAIN_TRANSIENT
+                && focusGain != AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK
+                && focusGain != AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE) {
+            throw new IllegalArgumentException("Illegal audio focus type " + focusGain);
+        }
+        mAudioFocusType = focusGain;
+    }
+
+    /**
+     * Sets the {@link AudioAttributes} to be used during the playback of the video.
+     * @param attributes non-null <code>AudioAttributes</code>.
+     */
+    public void setAudioAttributes(@NonNull AudioAttributes attributes) {
+        if (attributes == null) {
+            throw new IllegalArgumentException("Illegal null AudioAttributes");
+        }
+        mAudioAttributes = attributes;
+    }
+
+    /**
      * Adds an external subtitle source file (from the provided input stream.)
      *
      * Note that a single external subtitle source may contain multiple or no
@@ -301,8 +353,7 @@
             mMediaPlayer = null;
             mCurrentState = STATE_IDLE;
             mTargetState  = STATE_IDLE;
-            AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
-            am.abandonAudioFocus(null);
+            mAudioManager.abandonAudioFocus(null);
         }
     }
 
@@ -315,8 +366,10 @@
         // called start() previously
         release(false);
 
-        AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
-        am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
+        if (mAudioFocusType != AudioManager.AUDIOFOCUS_NONE) {
+            // TODO this should have a focus listener
+            mAudioManager.requestAudioFocus(null, mAudioAttributes, mAudioFocusType, 0 /*flags*/);
+        }
 
         try {
             mMediaPlayer = new MediaPlayer();
@@ -345,7 +398,7 @@
             mCurrentBufferPercentage = 0;
             mMediaPlayer.setDataSource(mContext, mUri, mHeaders);
             mMediaPlayer.setDisplay(mSurfaceHolder);
-            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
+            mMediaPlayer.setAudioAttributes(mAudioAttributes);
             mMediaPlayer.setScreenOnWhilePlaying(true);
             mMediaPlayer.prepareAsync();
 
@@ -482,6 +535,9 @@
             if (mOnCompletionListener != null) {
                 mOnCompletionListener.onCompletion(mMediaPlayer);
             }
+            if (mAudioFocusType != AudioManager.AUDIOFOCUS_NONE) {
+                mAudioManager.abandonAudioFocus(null);
+            }
         }
     };
 
@@ -644,8 +700,9 @@
             if (cleartargetstate) {
                 mTargetState  = STATE_IDLE;
             }
-            AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
-            am.abandonAudioFocus(null);
+            if (mAudioFocusType != AudioManager.AUDIOFOCUS_NONE) {
+                mAudioManager.abandonAudioFocus(null);
+            }
         }
     }
 
diff --git a/core/java/com/android/internal/util/Predicate.java b/core/java/com/android/internal/util/Predicate.java
index bc6d6b3..1b5eaff 100644
--- a/core/java/com/android/internal/util/Predicate.java
+++ b/core/java/com/android/internal/util/Predicate.java
@@ -25,7 +25,10 @@
  * <p/>
  * Implementors of Predicate which may cause side effects upon evaluation are
  * strongly encouraged to state this fact clearly in their API documentation.
+ *
+ * @deprecated Use {@code java.util.function.Predicate} instead.
  */
+@Deprecated
 public interface Predicate<T> {
 
     boolean apply(T t);
diff --git a/core/java/com/android/internal/view/IInputConnectionWrapper.java b/core/java/com/android/internal/view/IInputConnectionWrapper.java
index 555263d..28291ae 100644
--- a/core/java/com/android/internal/view/IInputConnectionWrapper.java
+++ b/core/java/com/android/internal/view/IInputConnectionWrapper.java
@@ -496,6 +496,7 @@
                 } finally {
                     args.recycle();
                 }
+                return;
             }
             case DO_REQUEST_UPDATE_CURSOR_ANCHOR_INFO: {
                 SomeArgs args = (SomeArgs)msg.obj;
diff --git a/core/jni/Android.mk b/core/jni/Android.mk
index 0c07192..3dd2498 100644
--- a/core/jni/Android.mk
+++ b/core/jni/Android.mk
@@ -220,7 +220,6 @@
     external/skia/src/effects \
     external/skia/src/image \
     external/skia/src/images \
-    external/skia/src/utils \
     external/sqlite/dist \
     external/sqlite/android \
     external/tremor/Tremor \
diff --git a/core/jni/android/graphics/BitmapFactory.cpp b/core/jni/android/graphics/BitmapFactory.cpp
index 30d6337..417ef8a0 100644
--- a/core/jni/android/graphics/BitmapFactory.cpp
+++ b/core/jni/android/graphics/BitmapFactory.cpp
@@ -8,7 +8,6 @@
 #include "SkBRDAllocator.h"
 #include "SkFrontBufferedStream.h"
 #include "SkMath.h"
-#include "SkOpts.h"
 #include "SkPixelRef.h"
 #include "SkStream.h"
 #include "SkUtils.h"
@@ -229,45 +228,6 @@
            needsFineScale(fullSize.height(), decodedSize.height(), sampleSize);
 }
 
-static inline SkAlphaType computeDecodeAlphaType(SkColorType colorType, SkAlphaType alphaType) {
-#ifndef ANDROID_ENABLE_LINEAR_BLENDING
-    // Skia premultiplies linearly.  Until the framework enables linear blending,
-    // it expects a legacy premultiply.
-    if (kPremul_SkAlphaType == alphaType && kRGBA_F16_SkColorType != colorType) {
-        return kUnpremul_SkAlphaType;
-    }
-#endif
-
-    return alphaType;
-}
-
-static inline void premultiplyIfNecessary(SkBitmap* bitmap, SkPMColor* colorPtr, int* colorCount,
-        SkAlphaType alphaType, bool requireUnpremultiplied) {
-#ifndef ANDROID_ENABLE_LINEAR_BLENDING
-    if (kUnpremul_SkAlphaType != alphaType || requireUnpremultiplied) {
-        return;
-    }
-
-    switch (bitmap->colorType()) {
-        case kN32_SkColorType:
-            for (int y = 0; y < bitmap->height(); y++) {
-                SkOpts::RGBA_to_rgbA(bitmap->getAddr32(0, y), bitmap->getAddr32(0, y),
-                    bitmap->width());
-            }
-
-            return;
-        case kIndex_8_SkColorType:
-            SkOpts::RGBA_to_rgbA(colorPtr, colorPtr, *colorCount);
-            return;
-        default:
-            // kRGBA_F16 will be premultiplied by the codec if necessary.
-            // kGray_8 (alias kAlpha_8) and k565 are opaque.
-            LOG_ALWAYS_FATAL("Should be unreachable - no need for legacy premultiply.");
-            return;
-    }
-#endif
-}
-
 static jobject doDecode(JNIEnv* env, SkStreamRewindable* stream, jobject padding, jobject options) {
     // This function takes ownership of the input stream.  Since the SkAndroidCodec
     // will take ownership of the stream, we don't necessarily need to take ownership
@@ -450,15 +410,13 @@
     }
 
     SkAlphaType alphaType = codec->computeOutputAlphaType(requireUnpremultiplied);
-    SkAlphaType decodeAlphaType = computeDecodeAlphaType(decodeColorType, alphaType);
 
     const SkImageInfo decodeInfo = SkImageInfo::Make(size.width(), size.height(),
-            decodeColorType, decodeAlphaType, codec->computeOutputColorSpace(decodeColorType));
-
-    SkImageInfo bitmapInfo = decodeInfo.makeAlphaType(alphaType);
+            decodeColorType, alphaType, codec->computeOutputColorSpace(decodeColorType));
 
     // For wide gamut images, we will leave the color space on the SkBitmap.  Otherwise,
     // use the default.
+    SkImageInfo bitmapInfo = decodeInfo;
     sk_sp<SkColorSpace> srgb =
             SkColorSpace::MakeRGB(SkColorSpace::kSRGB_RenderTargetGamma,
                                   SkColorSpace::kSRGB_Gamut,
@@ -502,8 +460,6 @@
         default:
             return nullObjectReturn("codec->getAndroidPixels() failed.");
     }
-    premultiplyIfNecessary(&decodingBitmap, colorPtr, colorCount, decodeAlphaType,
-            requireUnpremultiplied);
 
     jbyteArray ninePatchChunk = NULL;
     if (peeker.mPatch != NULL) {
diff --git a/core/jni/android_os_seccomp.cpp b/core/jni/android_os_seccomp.cpp
index 45d5061..f1bc76e 100644
--- a/core/jni/android_os_seccomp.cpp
+++ b/core/jni/android_os_seccomp.cpp
@@ -65,11 +65,6 @@
 
 #pragma clang diagnostic pop
 
-inline static void AllowSyscall(filter& f, __u32 num) {
-    f.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, num, 0, 1));
-    Allow(f);
-}
-
 inline static void ExamineSyscall(filter& f) {
     f.push_back(BPF_STMT(BPF_LD|BPF_W|BPF_ABS, syscall_nr));
 }
@@ -125,34 +120,6 @@
     // arm64-only filter - autogenerated from bionic syscall usage
     for (size_t i = 0; i < arm64_filter_size; ++i)
         f.push_back(arm64_filter[i]);
-
-    // Syscalls needed to boot Android
-    AllowSyscall(f, 41);  // __NR_pivot_root
-    AllowSyscall(f, 31);  // __NR_ioprio_get
-    AllowSyscall(f, 30);  // __NR_ioprio_set
-    AllowSyscall(f, 178); // __NR_gettid
-    AllowSyscall(f, 98);  // __NR_futex
-    AllowSyscall(f, 220); // __NR_clone
-    AllowSyscall(f, 139); // __NR_rt_sigreturn
-    AllowSyscall(f, 240); // __NR_rt_tgsigqueueinfo
-    AllowSyscall(f, 128); // __NR_restart_syscall
-    AllowSyscall(f, 278); // __NR_getrandom
-
-    // Needed for performance tools
-    AllowSyscall(f, 241); // __NR_perf_event_open
-
-    // Needed for strace
-    AllowSyscall(f, 130); // __NR_tkill
-
-    // Needed for kernel to restart syscalls
-    AllowSyscall(f, 128); // __NR_restart_syscall
-
-    // b/35034743
-    AllowSyscall(f, 267); // __NR_syncfs
-
-    // b/34763393
-    AllowSyscall(f, 277); // __NR_seccomp
-
     Trap(f);
 
     if (SetValidateArchitectureJumpTarget(offset_to_32bit_filter, f) != 0)
@@ -164,64 +131,6 @@
     // arm32 filter - autogenerated from bionic syscall usage
     for (size_t i = 0; i < arm_filter_size; ++i)
         f.push_back(arm_filter[i]);
-
-    // Syscalls needed to boot android
-    AllowSyscall(f, 120); // __NR_clone
-    AllowSyscall(f, 240); // __NR_futex
-    AllowSyscall(f, 119); // __NR_sigreturn
-    AllowSyscall(f, 173); // __NR_rt_sigreturn
-    AllowSyscall(f, 363); // __NR_rt_tgsigqueueinfo
-    AllowSyscall(f, 224); // __NR_gettid
-
-    // Syscalls needed to run Chrome
-    AllowSyscall(f, 383); // __NR_seccomp - needed to start Chrome
-    AllowSyscall(f, 384); // __NR_getrandom - needed to start Chrome
-
-    // Syscalls needed to run GFXBenchmark
-    AllowSyscall(f, 190); // __NR_vfork
-
-    // Needed for strace
-    AllowSyscall(f, 238); // __NR_tkill
-
-    // Needed for kernel to restart syscalls
-    AllowSyscall(f, 0);   // __NR_restart_syscall
-
-    // Needed for debugging 32-bit Chrome
-    AllowSyscall(f, 42);  // __NR_pipe
-
-    // b/34732712
-    AllowSyscall(f, 364); // __NR_perf_event_open
-
-    // b/34651972
-    AllowSyscall(f, 33);  // __NR_access
-    AllowSyscall(f, 195); // __NR_stat64
-
-    // b/34813887
-    AllowSyscall(f, 5);   // __NR_open
-    AllowSyscall(f, 141); // __NR_getdents
-    AllowSyscall(f, 217); // __NR_getdents64
-
-    // b/34719286
-    AllowSyscall(f, 351); // __NR_eventfd
-
-    // b/34817266
-    AllowSyscall(f, 252); // __NR_epoll_wait
-
-    // Needed by sanitizers (b/34606909)
-    // 5 (__NR_open) and 195 (__NR_stat64) are also required, but they are
-    // already allowed.
-    AllowSyscall(f, 85);  // __NR_readlink
-
-    // b/34908783
-    AllowSyscall(f, 250); // __NR_epoll_create
-
-    // b/34979910
-    AllowSyscall(f, 8);   // __NR_creat
-    AllowSyscall(f, 10);  // __NR_unlink
-
-    // b/35059702
-    AllowSyscall(f, 196); // __NR_lstat64
-
     Trap(f);
 
     return install_filter(f);
diff --git a/core/jni/android_view_SurfaceControl.cpp b/core/jni/android_view_SurfaceControl.cpp
index 0171562..a81901d 100644
--- a/core/jni/android_view_SurfaceControl.cpp
+++ b/core/jni/android_view_SurfaceControl.cpp
@@ -356,9 +356,9 @@
 }
 
 static void nativeSetMatrix(JNIEnv* env, jclass clazz, jlong nativeObject,
-        jfloat dsdx, jfloat dtdx, jfloat dsdy, jfloat dtdy) {
+        jfloat dsdx, jfloat dtdx, jfloat dtdy, jfloat dsdy) {
     SurfaceControl* const ctrl = reinterpret_cast<SurfaceControl *>(nativeObject);
-    status_t err = ctrl->setMatrix(dsdx, dtdx, dsdy, dtdy);
+    status_t err = ctrl->setMatrix(dsdx, dtdx, dtdy, dsdy);
     if (err < 0 && err != NO_INIT) {
         doThrowIAE(env);
     }
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 9108f4a..64759ff 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -1795,7 +1795,7 @@
     <eat-comment />
 
     <!-- Allows an app to create windows using the type
-         {@link android.view.WindowManager.LayoutParams#TYPE_SYSTEM_ALERT},
+         {@link android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY},
          shown on top of all other apps.  Very few apps
          should use this permission; these windows are intended for
          system-level interaction with the user.
diff --git a/core/res/res/layout/autofill_save.xml b/core/res/res/layout/autofill_save.xml
index d55a012..8453cd35 100644
--- a/core/res/res/layout/autofill_save.xml
+++ b/core/res/res/layout/autofill_save.xml
@@ -14,44 +14,79 @@
      limitations under the License.
 -->
 
-<!-- TODO(b/33197203) remove hardcoded color once color is final -->
-<RelativeLayout
+<LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="match_parent"
+    android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:paddingStart="16dip"
     android:paddingEnd="16dip"
     android:paddingTop="16dip"
     android:paddingBottom="16dip"
-    android:background="#FDF8C8">
+    android:elevation="16dp"
+    android:background="?android:attr/colorBackground"
+    android:orientation="vertical">
 
-  <!-- TODO(b/33197203) use.R.string once final wording is done -->
-  <TextView
-      android:id="@+id/autofill_save_title"
-      android:layout_width="match_parent"
-      android:layout_height="wrap_content"
-      android:text="Save for autofill?"
-      android:singleLine="true"/>
+    <LinearLayout
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal">
 
-  <TextView
-      android:id="@+id/autofill_save_no"
-      android:layout_width="wrap_content"
-      android:layout_height="wrap_content"
-      android:layout_below="@+id/autofill_save_title"
-      android:layout_toLeftOf="@+id/autofill_save_yes"
-      android:layout_marginRight="16dip"
-      android:text="No thanks"
-      android:textAllCaps="true"
-      android:singleLine="true"/>
+        <TextView
+            android:id="@+id/autofill_save_title"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="@string/autofill_save_title"
+            android:singleLine="true">
+        </TextView>
 
-    <TextView
-      android:id="@+id/autofill_save_yes"
-      android:layout_width="wrap_content"
-      android:layout_height="wrap_content"
-      android:layout_below="@+id/autofill_save_title"
-      android:layout_alignParentRight="true"
-      android:text="Save"
-      android:textAllCaps="true"
-      android:singleLine="true"/>
+        <Space
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:layout_weight="1"
+            android:visibility="invisible" >
+        </Space>
 
-</RelativeLayout>
+        <ImageView
+            android:id="@+id/autofill_save_close"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:src="@android:drawable/ic_close"
+            android:background="?android:attr/selectableItemBackgroundBorderless">
+        </ImageView>
+
+    </LinearLayout>
+
+    <com.android.internal.widget.ButtonBarLayout
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_gravity="end"
+        android:layout_marginTop="16dp"
+        android:layout_weight="1"
+        android:orientation="horizontal">
+
+        <Space
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:layout_weight="1"
+            android:visibility="invisible" >
+        </Space>
+
+        <Button
+            android:id="@+id/autofill_save_no"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            style="?android:attr/buttonBarButtonStyle"
+            android:text="@string/autofill_save_no" >
+        </Button>
+
+        <Button
+            android:id="@+id/autofill_save_yes"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            style="?android:attr/buttonBarButtonStyle"
+            android:text="@string/autofill_save_yes" >
+        </Button>
+
+   </com.android.internal.widget.ButtonBarLayout>
+
+</LinearLayout>
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index be0b516..d233e24 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -2612,6 +2612,10 @@
     <!-- True if the device supports split screen as a form of multi-window. -->
     <bool name="config_supportsSplitScreenMultiWindow">true</bool>
 
+    <!-- True if the device has no home screen. That is a launcher activity
+         where the user can launch other applications from.  -->
+    <bool name="config_noHomeScreen">false</bool>
+
     <!-- True if the device requires AppWidgetService even if it does not have
          the PackageManager.FEATURE_APP_WIDGETS feature -->
     <bool name="config_enableAppWidgetService">false</bool>
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index f6da660..6abc009 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -4510,4 +4510,11 @@
     <!-- Accessibility string used for describing the button in time picker that changes the dialog to circular clock mode. [CHAR LIMIT=NONE] -->
     <string name="time_picker_radial_mode_description">Switch to clock mode for the time input.</string>
 
+    <!-- Title for the auto-fill save dialog shown when the user entered savable text [CHAR LIMIT=NONE] -->
+    <string name="autofill_save_title">Save to <xliff:g id="label" example="MyPass">%1$s</xliff:g>?</string>
+    <!-- Label for the auto-fill save button [CHAR LIMIT=NONE] -->
+    <string name="autofill_save_yes">Save</string>
+    <!-- Label for the auto-fill cancel button [CHAR LIMIT=NONE] -->
+    <string name="autofill_save_no">No thanks</string>
+
 </resources>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index adca052..e7d3ec9 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -312,6 +312,7 @@
   <java-symbol type="bool" name="config_freeformWindowManagement" />
   <java-symbol type="bool" name="config_supportsMultiWindow" />
   <java-symbol type="bool" name="config_supportsSplitScreenMultiWindow" />
+  <java-symbol type="bool" name="config_noHomeScreen" />
   <java-symbol type="bool" name="config_guestUserEphemeral" />
   <java-symbol type="bool" name="config_localDisplaysMirrorContent" />
   <java-symbol type="integer" name="config_defaultDisplayDefaultColorMode" />
@@ -2841,6 +2842,10 @@
   <java-symbol type="id" name="autofill_save_title" />
   <java-symbol type="id" name="autofill_save_no" />
   <java-symbol type="id" name="autofill_save_yes" />
+  <java-symbol type="id" name="autofill_save_close" />
+  <java-symbol type="string" name="autofill_save_title" />
+  <java-symbol type="string" name="autofill_save_yes" />
+  <java-symbol type="string" name="autofill_save_no" />
 
   <!-- Accessibility fingerprint gestures -->
   <java-symbol type="string" name="capability_title_canCaptureFingerprintGestures" />
diff --git a/core/tests/coretests/src/android/net/NetworkScorerAppManagerTest.java b/core/tests/coretests/src/android/net/NetworkScorerAppManagerTest.java
index ce5d3ef..347024d 100644
--- a/core/tests/coretests/src/android/net/NetworkScorerAppManagerTest.java
+++ b/core/tests/coretests/src/android/net/NetworkScorerAppManagerTest.java
@@ -23,12 +23,14 @@
 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.ActivityInfo;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.content.pm.ServiceInfo;
 import android.content.res.Resources;
 import android.net.NetworkScorerAppManager.NetworkScorerAppData;
+import android.os.Bundle;
 import android.provider.Settings;
 import android.test.InstrumentationTestCase;
 
@@ -154,6 +156,62 @@
         assertEquals(924, activeScorer.packageUid);
     }
 
+    public void testGetActiveScorer_providerAvailable_enableUseOpenWifiActivityNotSet()
+            throws Exception {
+        final ComponentName recoComponent = new ComponentName("package1", "class1");
+        setNetworkRecommendationPackageNames(recoComponent.getPackageName());
+        mockScoreNetworksGranted(recoComponent.getPackageName());
+        mockRecommendationServiceAvailable(recoComponent, 924 /* packageUid */,
+                null /* enableUseOpenWifiPackageActivityPackage*/);
+
+        ContentResolver cr = mTargetContext.getContentResolver();
+        Settings.Global.putInt(cr, Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED, 1);
+
+        final NetworkScorerAppData activeScorer = mNetworkScorerAppManager.getActiveScorer();
+        assertNotNull(activeScorer);
+        assertEquals(recoComponent, activeScorer.getRecommendationServiceComponent());
+        assertEquals(924, activeScorer.packageUid);
+        assertNull(activeScorer.getEnableUseOpenWifiActivity());
+    }
+
+    public void testGetActiveScorer_providerAvailable_enableUseOpenWifiActivityNotResolved()
+            throws Exception {
+        final ComponentName recoComponent = new ComponentName("package1", "class1");
+        setNetworkRecommendationPackageNames(recoComponent.getPackageName());
+        mockScoreNetworksGranted(recoComponent.getPackageName());
+        mockRecommendationServiceAvailable(recoComponent, 924 /* packageUid */,
+                "package2" /* enableUseOpenWifiPackageActivityPackage*/);
+
+        ContentResolver cr = mTargetContext.getContentResolver();
+        Settings.Global.putInt(cr, Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED, 1);
+
+        final NetworkScorerAppData activeScorer = mNetworkScorerAppManager.getActiveScorer();
+        assertNotNull(activeScorer);
+        assertEquals(recoComponent, activeScorer.getRecommendationServiceComponent());
+        assertEquals(924, activeScorer.packageUid);
+        assertNull(activeScorer.getEnableUseOpenWifiActivity());
+    }
+
+    public void testGetActiveScorer_providerAvailable_enableUseOpenWifiActivityResolved()
+            throws Exception {
+        final ComponentName recoComponent = new ComponentName("package1", "class1");
+        final ComponentName enableUseOpenWifiComponent = new ComponentName("package2", "class2");
+        setNetworkRecommendationPackageNames(recoComponent.getPackageName());
+        mockScoreNetworksGranted(recoComponent.getPackageName());
+        mockRecommendationServiceAvailable(recoComponent, 924 /* packageUid */,
+                enableUseOpenWifiComponent.getPackageName());
+        mockEnableUseOpenWifiActivity(enableUseOpenWifiComponent);
+
+        ContentResolver cr = mTargetContext.getContentResolver();
+        Settings.Global.putInt(cr, Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED, 1);
+
+        final NetworkScorerAppData activeScorer = mNetworkScorerAppManager.getActiveScorer();
+        assertNotNull(activeScorer);
+        assertEquals(recoComponent, activeScorer.getRecommendationServiceComponent());
+        assertEquals(924, activeScorer.packageUid);
+        assertEquals(enableUseOpenWifiComponent, activeScorer.getEnableUseOpenWifiActivity());
+    }
+
     public void testGetActiveScorer_providerNotAvailable()
             throws Exception {
         ContentResolver cr = mTargetContext.getContentResolver();
@@ -194,14 +252,25 @@
     }
 
     private void mockRecommendationServiceAvailable(final ComponentName compName, int packageUid) {
+        mockRecommendationServiceAvailable(compName, packageUid, null);
+    }
+
+    private void mockRecommendationServiceAvailable(final ComponentName compName, int packageUid,
+            String enableUseOpenWifiActivityPackage) {
         final ResolveInfo serviceInfo = new ResolveInfo();
         serviceInfo.serviceInfo = new ServiceInfo();
         serviceInfo.serviceInfo.name = compName.getClassName();
         serviceInfo.serviceInfo.packageName = compName.getPackageName();
         serviceInfo.serviceInfo.applicationInfo = new ApplicationInfo();
         serviceInfo.serviceInfo.applicationInfo.uid = packageUid;
+        if (enableUseOpenWifiActivityPackage != null) {
+            serviceInfo.serviceInfo.metaData = new Bundle();
+            serviceInfo.serviceInfo.metaData.putString(
+                    NetworkScoreManager.USE_OPEN_WIFI_PACKAGE_META_DATA,
+                    enableUseOpenWifiActivityPackage);
+        }
 
-        final int flags = 0;
+        final int flags = PackageManager.GET_META_DATA;
         when(mMockPm.resolveService(
                 Mockito.argThat(new ArgumentMatcher<Intent>() {
                     @Override
@@ -213,4 +282,22 @@
                     }
                 }), Mockito.eq(flags))).thenReturn(serviceInfo);
     }
+
+    private void mockEnableUseOpenWifiActivity(final ComponentName useOpenWifiComp) {
+        final ResolveInfo resolveActivityInfo = new ResolveInfo();
+        resolveActivityInfo.activityInfo = new ActivityInfo();
+        resolveActivityInfo.activityInfo.name = useOpenWifiComp.getClassName();
+        resolveActivityInfo.activityInfo.packageName = useOpenWifiComp.getPackageName();
+
+        final int flags = 0;
+        when(mMockPm.resolveActivity(
+                Mockito.argThat(new ArgumentMatcher<Intent>() {
+                    @Override
+                    public boolean matches(Object object) {
+                        Intent intent = (Intent) object;
+                        return NetworkScoreManager.ACTION_CUSTOM_ENABLE.equals(intent.getAction())
+                                && useOpenWifiComp.getPackageName().equals(intent.getPackage());
+                    }
+                }), Mockito.eq(flags))).thenReturn(resolveActivityInfo);
+    }
 }
diff --git a/core/tests/coretests/src/android/os/FileUtilsTest.java b/core/tests/coretests/src/android/os/FileUtilsTest.java
index bd90079..5c7da70 100644
--- a/core/tests/coretests/src/android/os/FileUtilsTest.java
+++ b/core/tests/coretests/src/android/os/FileUtilsTest.java
@@ -311,6 +311,28 @@
         assertNameEquals("test.foo (1).bar", FileUtils.buildUniqueFile(mTarget, "test.foo.bar"));
     }
 
+    public void testRoundStorageSize() throws Exception {
+        final long M128 = 134217728L;
+        final long M256 = M128 * 2;
+        final long M512 = M256 * 2;
+        final long M1024 = M512 * 2;
+        final long G16 = M1024 * 16;
+        final long G32 = M1024 * 32;
+        final long G64 = M1024 * 64;
+
+        assertEquals(M128, FileUtils.roundStorageSize(M128));
+        assertEquals(M256, FileUtils.roundStorageSize(M128 + 1));
+        assertEquals(M256, FileUtils.roundStorageSize(M256 - 1));
+        assertEquals(M256, FileUtils.roundStorageSize(M256));
+        assertEquals(M512, FileUtils.roundStorageSize(M256 + 1));
+
+        assertEquals(G16, FileUtils.roundStorageSize(G16));
+        assertEquals(G32, FileUtils.roundStorageSize(G16 + 1));
+        assertEquals(G32, FileUtils.roundStorageSize(G32 - 1));
+        assertEquals(G32, FileUtils.roundStorageSize(G32));
+        assertEquals(G64, FileUtils.roundStorageSize(G32 + 1));
+    }
+
     private static void assertNameEquals(String expected, File actual) {
         assertEquals(expected, actual.getName());
     }
diff --git a/core/tests/coretests/src/android/provider/SettingsBackupTest.java b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
index 8e29d63..da6a294 100644
--- a/core/tests/coretests/src/android/provider/SettingsBackupTest.java
+++ b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
@@ -179,6 +179,7 @@
                     Settings.Global.DROPBOX_TAG_PREFIX,
                     Settings.Global.EMERGENCY_AFFORDANCE_NEEDED,
                     Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED,
+                    Settings.Global.ENABLE_CACHE_QUOTA_CALCULATION,
                     Settings.Global.ENABLE_CELLULAR_ON_BOOT,
                     Settings.Global.ENABLE_DISKSTATS_LOGGING,
                     Settings.Global.ENABLE_EPHEMERAL_FEATURE,
@@ -324,7 +325,6 @@
                     Settings.Global.USE_GOOGLE_MAIL,
                     Settings.Global.VT_IMS_ENABLED,
                     Settings.Global.WAIT_FOR_DEBUGGER,
-                    Settings.Global.WAIT_FOR_NETWORK_TIMEOUT_MS,
                     Settings.Global.WARNING_TEMPERATURE,
                     Settings.Global.WEBVIEW_DATA_REDUCTION_PROXY_KEY,
                     Settings.Global.WEBVIEW_FALLBACK_LOGIC_ENABLED,
diff --git a/data/etc/platform.xml b/data/etc/platform.xml
index 344f3c8..6248856 100644
--- a/data/etc/platform.xml
+++ b/data/etc/platform.xml
@@ -60,7 +60,6 @@
     </permission>
 
     <permission name="android.permission.WRITE_MEDIA_STORAGE" >
-        <group gid="media_rw" />
         <group gid="sdcard_rw" />
     </permission>
 
diff --git a/legacy-test/Android.mk b/legacy-test/Android.mk
index 0a814f3..05fec5e 100644
--- a/legacy-test/Android.mk
+++ b/legacy-test/Android.mk
@@ -50,5 +50,5 @@
 LOCAL_SRC_FILES := src/android/test/PerformanceTestCase.java
 LOCAL_MODULE := legacy-performance-test-hostdex
 
-include $(BUILD_HOST_DALVIK_JAVA_LIBRARY)
+include $(BUILD_HOST_DALVIK_STATIC_JAVA_LIBRARY)
 endif  # HOST_OS == linux
diff --git a/libs/hwui/renderthread/EglManager.cpp b/libs/hwui/renderthread/EglManager.cpp
index 860725b..44af5fd 100644
--- a/libs/hwui/renderthread/EglManager.cpp
+++ b/libs/hwui/renderthread/EglManager.cpp
@@ -133,7 +133,7 @@
         LOG_ALWAYS_FATAL_IF(!glInterface.get());
 
         GrContextOptions options;
-        options.fDisableDistanceFieldPaths = true;
+        options.fGpuPathRenderers &= ~GrContextOptions::GpuPathRenderers::kDistanceField;
         options.fAllowPathMaskCaching = true;
         mRenderThread.setGrContext(GrContext::Create(GrBackend::kOpenGL_GrBackend,
                 (GrBackendContext)glInterface.get(), options));
diff --git a/libs/hwui/tests/unit/FrameBuilderTests.cpp b/libs/hwui/tests/unit/FrameBuilderTests.cpp
index a391d1e..95d9459 100644
--- a/libs/hwui/tests/unit/FrameBuilderTests.cpp
+++ b/libs/hwui/tests/unit/FrameBuilderTests.cpp
@@ -579,7 +579,7 @@
         SkPaint textPaint;
         textPaint.setAntiAlias(true);
         textPaint.setTextSize(20);
-        textPaint.setStrikeThruText(true);
+        textPaint.setFlags(textPaint.getFlags() | SkPaint::kStrikeThruText_ReserveFlag);
         textPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
         for (int i = 0; i < LOOPS; i++) {
             TestUtils::drawUtf8ToCanvas(&canvas, "test text", textPaint, 10, 100 * (i + 1));
diff --git a/libs/hwui/tests/unit/RecordingCanvasTests.cpp b/libs/hwui/tests/unit/RecordingCanvasTests.cpp
index 669f03c..b2ea9ac 100644
--- a/libs/hwui/tests/unit/RecordingCanvasTests.cpp
+++ b/libs/hwui/tests/unit/RecordingCanvasTests.cpp
@@ -200,8 +200,18 @@
         paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
         for (int i = 0; i < 2; i++) {
             for (int j = 0; j < 2; j++) {
-                paint.setUnderlineText(i != 0);
-                paint.setStrikeThruText(j != 0);
+                uint32_t flags = paint.getFlags();
+                if (i != 0) {
+                    flags |= SkPaint::kUnderlineText_ReserveFlag;
+                } else {
+                    flags &= ~SkPaint::kUnderlineText_ReserveFlag;
+                }
+                if (j != 0) {
+                    flags |= SkPaint::kStrikeThruText_ReserveFlag;
+                } else {
+                    flags &= ~SkPaint::kStrikeThruText_ReserveFlag;
+                }
+                paint.setFlags(flags);
                 TestUtils::drawUtf8ToCanvas(&canvas, "test text", paint, 25, 25);
             }
         }
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java
index a4f2a7e..95d354b 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -1981,8 +1981,7 @@
     }
 
     /**
-     * @hide
-     * Used to indicate no audio focus has been gained or lost.
+     * Used to indicate no audio focus has been gained or lost, or requested.
      */
     public static final int AUDIOFOCUS_NONE = 0;
 
diff --git a/media/java/android/media/AudioPlaybackConfiguration.java b/media/java/android/media/AudioPlaybackConfiguration.java
index dd9c6a7..6b8a279 100644
--- a/media/java/android/media/AudioPlaybackConfiguration.java
+++ b/media/java/android/media/AudioPlaybackConfiguration.java
@@ -366,11 +366,18 @@
      * @param pw
      */
     public void dump(PrintWriter pw) {
-        pw.println("  ID:" + mPlayerIId
-                + " -- type:" + toLogFriendlyPlayerType(mPlayerType)
-                + " -- u/pid:" + mClientUid +"/" + mClientPid
-                + " -- state:" + toLogFriendlyPlayerState(mPlayerState)
-                + " -- attr:" + mPlayerAttr);
+        pw.println("  " + toLogFriendlyString(this));
+    }
+
+    /**
+     * @hide
+     */
+    public static String toLogFriendlyString(AudioPlaybackConfiguration apc) {
+        return new String("ID:" + apc.mPlayerIId
+                + " -- type:" + toLogFriendlyPlayerType(apc.mPlayerType)
+                + " -- u/pid:" + apc.mClientUid +"/" + apc.mClientPid
+                + " -- state:" + toLogFriendlyPlayerState(apc.mPlayerState)
+                + " -- attr:" + apc.mPlayerAttr);
     }
 
     public static final Parcelable.Creator<AudioPlaybackConfiguration> CREATOR
diff --git a/media/java/android/media/IAudioService.aidl b/media/java/android/media/IAudioService.aidl
index fa4796a..5855984 100644
--- a/media/java/android/media/IAudioService.aidl
+++ b/media/java/android/media/IAudioService.aidl
@@ -192,7 +192,7 @@
 
     oneway void releasePlayer(in int piid);
 
-    void disableRingtoneSync();
+    void disableRingtoneSync(in int userId);
 
     int getFocusRampTimeMs(in int focusGain, in AudioAttributes attr);
 
diff --git a/media/java/android/media/PlayerBase.java b/media/java/android/media/PlayerBase.java
index b397b45..1f5986f 100644
--- a/media/java/android/media/PlayerBase.java
+++ b/media/java/android/media/PlayerBase.java
@@ -58,7 +58,7 @@
     protected float mAuxEffectSendLevel = 0.0f;
 
     // for AppOps
-    private IAppOpsService mAppOps;
+    private IAppOpsService mAppOps; // may be null
     private IAppOpsCallback mAppOpsCallback;
     private boolean mHasAppOpsPlayAudio = true; // sync'd on mLock
     private final Object mLock = new Object();
@@ -251,7 +251,9 @@
             Log.e(TAG, "Error talking to audio service, the player will still be tracked", e);
         }
         try {
-            mAppOps.stopWatchingMode(mAppOpsCallback);
+            if (mAppOps != null) {
+                mAppOps.stopWatchingMode(mAppOpsCallback);
+            }
         } catch (RemoteException e) {
             // nothing to do here, the object is supposed to be released anyway
         }
@@ -264,9 +266,12 @@
     void updateAppOpsPlayAudio_sync() {
         boolean oldHasAppOpsPlayAudio = mHasAppOpsPlayAudio;
         try {
-            final int mode = mAppOps.checkAudioOperation(AppOpsManager.OP_PLAY_AUDIO,
+            int mode = AppOpsManager.MODE_IGNORED;
+            if (mAppOps != null) {
+                mode = mAppOps.checkAudioOperation(AppOpsManager.OP_PLAY_AUDIO,
                     mAttributes.getUsage(),
                     Process.myUid(), ActivityThread.currentPackageName());
+            }
             mHasAppOpsPlayAudio = (mode == AppOpsManager.MODE_ALLOWED);
         } catch (RemoteException e) {
             mHasAppOpsPlayAudio = false;
diff --git a/media/java/android/media/RingtoneManager.java b/media/java/android/media/RingtoneManager.java
index 8a1027b..e774c71 100644
--- a/media/java/android/media/RingtoneManager.java
+++ b/media/java/android/media/RingtoneManager.java
@@ -103,10 +103,6 @@
      */
     public static final int TYPE_ALL = TYPE_RINGTONE | TYPE_NOTIFICATION | TYPE_ALARM;
 
-    private static final int[] RINGTONE_TYPES = {
-            TYPE_RINGTONE, TYPE_NOTIFICATION, TYPE_ALARM
-    };
-    
     // </attr>
     
     /**
@@ -773,30 +769,17 @@
     }
 
     /**
-     * Disables Settings.System.SYNC_PARENT_SOUNDS, copying the parent's ringtones to the current
-     * profile
+     * Disables Settings.System.SYNC_PARENT_SOUNDS.
      *
      * @hide
      */
-    @RequiresPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
     public static void disableSyncFromParent(Context userContext) {
-        // Must disable sync first so that ringtone copy below doesn't get redirected to parent
-        Settings.Secure.putIntForUser(userContext.getContentResolver(),
-                Settings.Secure.SYNC_PARENT_SOUNDS, 0 /* false */, userContext.getUserId());
-
-        // Copy ringtones from parent profile
-        UserManager um = UserManager.get(userContext);
-        UserInfo parentInfo = um.getProfileParent(userContext.getUserId());
-        if (parentInfo != null) {
-            final Context targetContext = createPackageContextAsUser(userContext, parentInfo.id);
-            if (targetContext != null) {
-                for (int ringtoneType : RINGTONE_TYPES) {
-                    Uri ringtoneUri = getActualDefaultRingtoneUri(targetContext, ringtoneType);
-                    // Add user id of parent so that custom ringtones can be read and played
-                    RingtoneManager.setActualDefaultRingtoneUri(userContext, ringtoneType,
-                            maybeAddUserId(ringtoneUri, parentInfo.id));
-                }
-            }
+        IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
+        IAudioService audioService = IAudioService.Stub.asInterface(b);
+        try {
+            audioService.disableRingtoneSync(userContext.getUserId());
+        } catch (RemoteException e) {
+            Log.e(TAG, "Unable to disable ringtone sync.");
         }
     }
 
@@ -851,22 +834,15 @@
      * @see #getActualDefaultRingtoneUri(Context, int)
      */
     public static void setActualDefaultRingtoneUri(Context context, int type, Uri ringtoneUri) {
-        final ContentResolver resolver = context.getContentResolver();
-
-        if (Settings.Secure.getString(resolver, Settings.Secure.SYNC_PARENT_SOUNDS).equals("1")) {
-            // Sync is enabled, so we need to disable it
-            IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
-            IAudioService audioService = IAudioService.Stub.asInterface(b);
-            try {
-                audioService.disableRingtoneSync();
-            } catch (RemoteException e) {
-                Log.e(TAG, "Unable to disable ringtone sync.");
-                return;
-            }
-        }
-
         String setting = getSettingForType(type);
         if (setting == null) return;
+
+        final ContentResolver resolver = context.getContentResolver();
+        if (Settings.Secure.getIntForUser(resolver, Settings.Secure.SYNC_PARENT_SOUNDS, 0,
+                    context.getUserId()) == 1) {
+            // Parent sound override is enabled. Disable it using the audio service.
+            disableSyncFromParent(context);
+        }
         if(!isInternalRingtoneUri(ringtoneUri)) {
             ringtoneUri = ContentProvider.maybeAddUserId(ringtoneUri, context.getUserId());
         }
diff --git a/packages/CarrierDefaultApp/AndroidManifest.xml b/packages/CarrierDefaultApp/AndroidManifest.xml
index e2080b0..d910920 100644
--- a/packages/CarrierDefaultApp/AndroidManifest.xml
+++ b/packages/CarrierDefaultApp/AndroidManifest.xml
@@ -31,7 +31,7 @@
     <application android:label="@string/app_name" >
         <receiver android:name="com.android.carrierdefaultapp.CarrierDefaultBroadcastReceiver">
             <intent-filter>
-                <action android:name="android.intent.action.CARRIER_SIGNAL_REDIRECTED" />
+                <action android:name="com.android.internal.telephony.CARRIER_SIGNAL_REDIRECTED" />
             </intent-filter>
         </receiver>
         <activity android:name="com.android.carrierdefaultapp.CaptivePortalLaunchActivity"
diff --git a/packages/CarrierDefaultApp/src/com/android/carrierdefaultapp/CaptivePortalLaunchActivity.java b/packages/CarrierDefaultApp/src/com/android/carrierdefaultapp/CaptivePortalLaunchActivity.java
index b7fde12..28251cb 100644
--- a/packages/CarrierDefaultApp/src/com/android/carrierdefaultapp/CaptivePortalLaunchActivity.java
+++ b/packages/CarrierDefaultApp/src/com/android/carrierdefaultapp/CaptivePortalLaunchActivity.java
@@ -79,7 +79,7 @@
     private void showConnectingProgressDialog() {
         mProgressDialog = new ProgressDialog(getApplicationContext());
         mProgressDialog.setMessage(getString(R.string.progress_dialogue_network_connection));
-        mProgressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
+        mProgressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
         mProgressDialog.show();
     }
 
diff --git a/packages/FakeOemFeatures/src/com/android/fakeoemfeatures/FakeApp.java b/packages/FakeOemFeatures/src/com/android/fakeoemfeatures/FakeApp.java
index 36ce7ce..c9e0d0a 100644
--- a/packages/FakeOemFeatures/src/com/android/fakeoemfeatures/FakeApp.java
+++ b/packages/FakeOemFeatures/src/com/android/fakeoemfeatures/FakeApp.java
@@ -108,14 +108,14 @@
             builder.setCancelable(false);
             builder.setPositiveButton("I understand", null);
             Dialog dialog = builder.create();
-            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
+            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
             dialog.show();
         }
 
         // Make a fake window that is always around eating graphics resources.
         FakeView view = new FakeView(this);
         WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
-                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
+                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                 | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
diff --git a/packages/FakeOemFeatures/src/com/android/fakeoemfeatures/FakeBackgroundService.java b/packages/FakeOemFeatures/src/com/android/fakeoemfeatures/FakeBackgroundService.java
index 5d1a398..ff09000 100644
--- a/packages/FakeOemFeatures/src/com/android/fakeoemfeatures/FakeBackgroundService.java
+++ b/packages/FakeOemFeatures/src/com/android/fakeoemfeatures/FakeBackgroundService.java
@@ -74,7 +74,7 @@
         // Make a fake window that is always around eating graphics resources.
         FakeView view = new FakeView(this);
         Dialog dialog = new Dialog(this, android.R.style.Theme_Holo_Dialog);
-        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
+        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
         dialog.getWindow().setFlags(
                 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
diff --git a/packages/SettingsLib/src/com/android/settingslib/drawer/TileUtils.java b/packages/SettingsLib/src/com/android/settingslib/drawer/TileUtils.java
index 6e10aab..f31c09b 100644
--- a/packages/SettingsLib/src/com/android/settingslib/drawer/TileUtils.java
+++ b/packages/SettingsLib/src/com/android/settingslib/drawer/TileUtils.java
@@ -33,7 +33,6 @@
 import android.os.UserManager;
 import android.provider.Settings.Global;
 import android.text.TextUtils;
-import android.util.ArrayMap;
 import android.util.Log;
 import android.util.Pair;
 
@@ -353,10 +352,7 @@
             CharSequence title = null;
             String summary = null;
             String keyHint = null;
-            String uriString = null;
             Uri uri = null;
-            // Several resources can be using the same provider. Only acquire a single provider.
-            Map<String, IContentProvider> providerMap = new ArrayMap<>();
 
             // Get the activity's meta-data
             try {
@@ -365,11 +361,7 @@
                 Bundle metaData = activityInfo.metaData;
 
                 if (res != null && metaData != null) {
-                    if (metaData.containsKey(META_DATA_PREFERENCE_ICON_URI)) {
-                        iconFromUri = getIconFromUri(context, activityInfo.packageName,
-                                metaData.getString(META_DATA_PREFERENCE_ICON_URI), providerMap);
-                    }
-                    if (iconFromUri == null && metaData.containsKey(META_DATA_PREFERENCE_ICON)) {
+                    if (metaData.containsKey(META_DATA_PREFERENCE_ICON)) {
                         icon = metaData.getInt(META_DATA_PREFERENCE_ICON);
                     }
                     if (metaData.containsKey(META_DATA_PREFERENCE_TITLE)) {
@@ -379,13 +371,7 @@
                             title = metaData.getString(META_DATA_PREFERENCE_TITLE);
                         }
                     }
-                    if (metaData.containsKey(META_DATA_PREFERENCE_SUMMARY_URI)) {
-                        summary = getTextFromUri(context,
-                                metaData.getString(META_DATA_PREFERENCE_SUMMARY_URI), providerMap,
-                                META_DATA_PREFERENCE_SUMMARY);
-                    }
-                    if (TextUtils.isEmpty(summary)
-                            && metaData.containsKey(META_DATA_PREFERENCE_SUMMARY)) {
+                    if (metaData.containsKey(META_DATA_PREFERENCE_SUMMARY)) {
                         if (metaData.get(META_DATA_PREFERENCE_SUMMARY) instanceof Integer) {
                             summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
                         } else {
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileUtilsTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileUtilsTest.java
index 1683901..2d3c4a7 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileUtilsTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileUtilsTest.java
@@ -282,26 +282,11 @@
         when(mPackageManager.queryIntentActivitiesAsUser(eq(intent), anyInt(), anyInt()))
                 .thenReturn(info);
 
-        Bundle bundle = new Bundle();
-        bundle.putInt("com.android.settings.icon", 161803);
-        bundle.putString("com.android.settings.icon_package", "abc");
-        bundle.putString("com.android.settings.summary", "dynamic-summary");
-        when(mIContentProvider.call(anyString(),
-                eq(TileUtils.getMethodFromUri(Uri.parse(URI_GET_ICON))), eq(URI_GET_ICON), any()))
-                .thenReturn(bundle);
-        when(mIContentProvider.call(anyString(),
-                eq(TileUtils.getMethodFromUri(Uri.parse(URI_GET_SUMMARY))), eq(URI_GET_SUMMARY),
-                any())).thenReturn(bundle);
-        when(mContentResolver.acquireProvider(anyString())).thenReturn(mIContentProvider);
-        when(mContentResolver.acquireProvider(any(Uri.class))).thenReturn(mIContentProvider);
-
         TileUtils.getTilesForIntent(mContext, UserHandle.CURRENT, intent, addedCache,
                 null /* defaultCategory */, outTiles, false /* usePriority */,
                 false /* checkCategory */);
 
         assertThat(outTiles.size()).isEqualTo(1);
-        assertThat(outTiles.get(0).icon.getResId()).isEqualTo(161803);
-        assertThat(outTiles.get(0).summary).isEqualTo("dynamic-summary");
     }
 
     public static ResolveInfo newInfo(boolean systemApp, String category) {
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index 521b8d7..5b4d2fd 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -88,6 +88,7 @@
 import java.security.SecureRandom;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collection;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Locale;
@@ -2617,6 +2618,8 @@
             if (isSecureSettingsKey(key)) {
                 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
                         sSecureCloneToManagedSettings);
+                maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
+                        sSystemCloneFromParentOnDependency.values());
             } else if (isSystemSettingsKey(key)) {
                 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
                         sSystemCloneToManagedSettings);
@@ -2626,7 +2629,7 @@
         }
 
         private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
-                Set<String> keysCloned) {
+                Collection<String> keysCloned) {
             if (keysCloned.contains(name)) {
                 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
                     // the notification for userId has already been sent.
@@ -2737,7 +2740,7 @@
         }
 
         private final class UpgradeController {
-            private static final int SETTINGS_VERSION = 141;
+            private static final int SETTINGS_VERSION = 142;
 
             private final int mUserId;
 
@@ -3262,6 +3265,26 @@
                     currentVersion = 141;
                 }
 
+                if (currentVersion == 141) {
+                    // Version 141: We added the notion of a default and whether the system set
+                    // the setting. This is used for resetting the internal state and we need
+                    // to make sure this value is updated for the existing settings, otherwise
+                    // we would delete system set settings while they should stay unmodified.
+                    SettingsState globalSettings = getGlobalSettingsLocked();
+                    ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings);
+                    globalSettings.persistSyncLocked();
+
+                    SettingsState secureSettings = getSecureSettingsLocked(mUserId);
+                    ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings);
+                    secureSettings.persistSyncLocked();
+
+                    SettingsState systemSettings = getSystemSettingsLocked(mUserId);
+                    ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings);
+                    systemSettings.persistSyncLocked();
+
+                    currentVersion = 142;
+                }
+
                 if (currentVersion != newVersion) {
                     Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
                             + newVersion + " left it at "
@@ -3277,5 +3300,22 @@
                 return currentVersion;
             }
         }
+
+        private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings) {
+            List<String> names = settings.getSettingNamesLocked();
+            final int nameCount = names.size();
+            for (int i = 0; i < nameCount; i++) {
+                String name = names.get(i);
+                Setting setting = settings.getSettingLocked(name);
+                if (setting.getDefaultValue() == null) {
+                    boolean systemSet = SettingsState.isSystemPackage(getContext(),
+                            setting.getPackageName());
+                    if (systemSet) {
+                        settings.insertSettingLocked(name, setting.getValue(),
+                                setting.getTag(), true, setting.getPackageName());
+                    }
+                }
+            }
+        }
     }
 }
diff --git a/packages/SystemUI/res/drawable/clipboard_empty.xml b/packages/SystemUI/res/drawable/clipboard_empty.xml
index 14a5ad2..33cd58c 100644
--- a/packages/SystemUI/res/drawable/clipboard_empty.xml
+++ b/packages/SystemUI/res/drawable/clipboard_empty.xml
@@ -1,25 +1,24 @@
 <!--
-    Copyright (C) 2016 The Android Open Source Project
+    Copyright (C) 2017 The Android Open Source Project
 
-    Licensed under the Apache License, Version 2.0 (the License);
+    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,
+    distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
 -->
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24.0dp"
-        android:height="24.0dp"
+        android:width="18.0dp"
+        android:height="18.0dp"
         android:viewportWidth="24.0"
         android:viewportHeight="24.0">
     <path
         android:fillColor="#FFFFFFFF"
-        android:pathData="M19.0,2.0l-4.18,0.0C14.0,0.84 13.3,0.0 12.0,0.0c-1.3,0.0 -2.0,0.84 -2.82,2.0L5.0,2.0c-1.1,0.0 -2.0,0.9 -2.0,2.0l0.0,16.0c0.0,1.0 0.9,2.0 2.0,2.0l14.0,0.0c1.1,0.0 2.0,-0.9 2.0,-2.0L21.0,4.0c0.0,-1.1 -0.9,-2.0 -2.0,-2.0zm-7.0,0.0c0.55,0.0 1.0,0.45 1.0,1.0s-0.45,1.0 -1.0,1.0 -1.0,-0.45 -1.0,-1.0 0.45,-1.0 1.0,-1.0zm7.0,18.0L5.0,20.0L5.0,4.0l2.0,0.0l0.0,3.0l10.0,0.0L17.0,4.0l2.0,0.0l0.0,16.0z" />
+        android:pathData="M16.0,1.0L4.0,1.0c-1.1,0.0 -2.0,0.9 -2.0,2.0l0.0,14.0l2.0,0.0L4.0,3.0l12.0,0.0L16.0,1.0zm3.0,4.0L8.0,5.0c-1.1,0.0 -2.0,0.9 -2.0,2.0l0.0,14.0c0.0,1.0 0.9,2.0 2.0,2.0l11.0,0.0c1.1,0.0 2.0,-0.9 2.0,-2.0L21.0,7.0c0.0,-1.1 -0.9,-2.0 -2.0,-2.0zm0.0,16.0L8.0,21.0L8.0,7.0l11.0,0.0l0.0,14.0z"/>
 </vector>
-
diff --git a/packages/SystemUI/res/drawable/clipboard_full.xml b/packages/SystemUI/res/drawable/clipboard_full.xml
index 2d46870..cb056da 100644
--- a/packages/SystemUI/res/drawable/clipboard_full.xml
+++ b/packages/SystemUI/res/drawable/clipboard_full.xml
@@ -1,25 +1,24 @@
 <!--
-    Copyright (C) 2016 The Android Open Source Project
+    Copyright (C) 2017 The Android Open Source Project
 
-    Licensed under the Apache License, Version 2.0 (the License);
+    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,
+    distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
 -->
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
-    android:width="24.0dp"
-    android:height="24.0dp"
-    android:viewportWidth="24.0"
-    android:viewportHeight="24.0">
+        android:width="18.0dp"
+        android:height="18.0dp"
+        android:viewportWidth="18.0"
+        android:viewportHeight="18.0">
     <path
-        android:fillColor="#FFFFFFFF"
-        android:pathData="M19.0,2.0l-4.18,0.0C14.0,0.84 13.3,0.0 12.0,0.0c-1.3,0.0 -2.0,0.84 -2.82,2.0L5.0,2.0c-1.1,0.0 -2.0,0.9 -2.0,2.0l0.0,16.0c0.0,1.0 0.9,2.0 2.0,2.0l14.0,0.0c1.1,0.0 2.0,-0.9 2.0,-2.0L21.0,4.0c0.0,-1.1 -0.9,-2.0 -2.0,-2.0zm-7.0,0.0c0.55,0.0 1.0,0.45 1.0,1.0s-0.45,1.0 -1.0,1.0 -1.0,-0.45 -1.0,-1.0 0.45,-1.0 1.0,-1.0zm7.0,18.0L5.0,20.0L5.0,4.0l2.0,0.0l0.0,3.0l10.0,0.0L17.0,4.0l2.0,0.0l0.0,16.0z M 6,8 l 12,0 l 0,11 l -12,0 l 0,-11z" />
+        android:pathData="M12.0,0.75L3.0,0.75c-0.82,0.0 -1.5,0.67 -1.5,1.5l0.0,10.5L3.0,12.75L3.0,2.25l9.0,0.0L12.0,0.75zM14.25,3.75L6.0,3.75c-0.83,0.0 -1.5,0.67 -1.5,1.5l0.0,10.5c0.0,0.83 0.67,1.5 1.5,1.5l8.25,0.0c0.83,0.0 1.5,-0.67 1.5,-1.5L15.75,5.25C15.75,4.42 15.08,3.75 14.25,3.75zM7.25,6.5l5.74,0.0l0.0,1.75L7.25,8.25L7.25,6.5zM11.76,14.5l-4.5,0.0l0.0,-1.75l4.5,0.0L11.76,14.5zM13.0,11.38L7.26,11.38L7.26,9.62L13.0,9.62L13.0,11.38z"
+        android:fillColor="#FFFFFF"/>
 </vector>
-
diff --git a/packages/SystemUI/res/drawable/ic_qs_signal_4g_plus.xml b/packages/SystemUI/res/drawable/ic_qs_signal_4g_plus.xml
index 54c52bf..782fbe4 100644
--- a/packages/SystemUI/res/drawable/ic_qs_signal_4g_plus.xml
+++ b/packages/SystemUI/res/drawable/ic_qs_signal_4g_plus.xml
@@ -16,8 +16,8 @@
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
         android:width="32.0dp"
         android:height="32.0dp"
-        android:viewportWidth="24.0"
-        android:viewportHeight="24.0">
+        android:viewportWidth="19.0"
+        android:viewportHeight="19.0">
     <path
         android:fillColor="#FFFFFFFF"
         android:pathData="M4.6,7.8l0.7,0.0l0.0,1.3L4.6,9.1L4.6,11.0L3.0,11.0L3.0,9.2L0.1,9.2L0.0,8.2l3.0,-5.7l1.7,0.0L4.6,7.8L4.6,7.8zM1.7,7.8L3.0,7.8l0.0,-3.0L2.9,5.0L1.7,7.8z"/>
diff --git a/packages/SystemUI/res/drawable/ic_qs_signal_e.xml b/packages/SystemUI/res/drawable/ic_qs_signal_e.xml
index dd0f271..4232126 100644
--- a/packages/SystemUI/res/drawable/ic_qs_signal_e.xml
+++ b/packages/SystemUI/res/drawable/ic_qs_signal_e.xml
@@ -16,9 +16,12 @@
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
         android:width="32dp"
         android:height="32dp"
-        android:viewportWidth="5.0"
-        android:viewportHeight="5.0">
+        android:viewportWidth="13.0"
+        android:viewportHeight="13.0">
+  <group
+    android:translateX="3.5" >
     <path
-        android:fillColor="#FFFFFFFF"
-        android:pathData="M4.400000,7.300000L1.700000,7.300000l0.000000,2.400000l3.300000,0.000000L5.000000,11.000000L0.000000,11.000000L0.000000,2.500000l4.900000,0.000000l0.000000,1.300000L1.700000,3.800000l0.000000,2.100000l2.800000,0.000000L4.500000,7.300000z"/>
+      android:fillColor="#FFFFFFFF"
+      android:pathData="M4.400000,7.300000L1.700000,7.300000l0.000000,2.400000l3.300000,0.000000L5.000000,11.000000L0.000000,11.000000L0.000000,2.500000l4.900000,0.000000l0.000000,1.300000L1.700000,3.800000l0.000000,2.100000l2.800000,0.000000L4.500000,7.300000z"/>
+  </group>
 </vector>
diff --git a/packages/SystemUI/res/drawable/ic_qs_signal_g.xml b/packages/SystemUI/res/drawable/ic_qs_signal_g.xml
index 3b47c0d..0c512d7 100644
--- a/packages/SystemUI/res/drawable/ic_qs_signal_g.xml
+++ b/packages/SystemUI/res/drawable/ic_qs_signal_g.xml
@@ -16,9 +16,11 @@
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
         android:width="32dp"
         android:height="32dp"
-        android:viewportWidth="7.0"
-        android:viewportHeight="7.0">
-    <path
-        android:fillColor="#FFFFFFFF"
-        android:pathData="M6.500000,9.900000c-0.200000,0.400000 -0.600000,0.700000 -1.000000,0.900000s-1.000000,0.400000 -1.800000,0.400000c-0.900000,0.000000 -1.700000,-0.300000 -2.200000,-0.800000S0.700000,9.000000 0.700000,7.900000L0.700000,5.600000c0.000000,-1.100000 0.300000,-1.900000 0.800000,-2.400000s1.200000,-0.800000 2.100000,-0.800000c1.000000,0.000000 1.700000,0.200000 2.100000,0.700000s0.700000,1.200000 0.700000,2.100000L4.700000,5.200000c0.000000,-0.500000 -0.100000,-0.900000 -0.200000,-1.100000S4.000000,3.700000 3.600000,3.700000c-0.400000,0.000000 -0.700000,0.200000 -0.900000,0.500000S2.300000,5.000000 2.300000,5.600000l0.000000,2.300000c0.000000,0.700000 0.100000,1.100000 0.300000,1.400000s0.600000,0.500000 1.000000,0.500000c0.300000,0.000000 0.600000,0.000000 0.700000,-0.100000s0.300000,-0.200000 0.400000,-0.300000L4.700000,7.800000L3.500000,7.800000L3.500000,6.600000l2.900000,0.000000L6.400000,9.900000z"/>
+        android:viewportWidth="13.0"
+        android:viewportHeight="13.0">
+    <group android:translateX="3.5" >
+      <path
+          android:fillColor="#FFFFFFFF"
+          android:pathData="M6.500000,9.900000c-0.200000,0.400000 -0.600000,0.700000 -1.000000,0.900000s-1.000000,0.400000 -1.800000,0.400000c-0.900000,0.000000 -1.700000,-0.300000 -2.200000,-0.800000S0.700000,9.000000 0.700000,7.900000L0.700000,5.600000c0.000000,-1.100000 0.300000,-1.900000 0.800000,-2.400000s1.200000,-0.800000 2.100000,-0.800000c1.000000,0.000000 1.700000,0.200000 2.100000,0.700000s0.700000,1.200000 0.700000,2.100000L4.700000,5.200000c0.000000,-0.500000 -0.100000,-0.900000 -0.200000,-1.100000S4.000000,3.700000 3.600000,3.700000c-0.400000,0.000000 -0.700000,0.200000 -0.900000,0.500000S2.300000,5.000000 2.300000,5.600000l0.000000,2.300000c0.000000,0.700000 0.100000,1.100000 0.300000,1.400000s0.600000,0.500000 1.000000,0.500000c0.300000,0.000000 0.600000,0.000000 0.700000,-0.100000s0.300000,-0.200000 0.400000,-0.300000L4.700000,7.800000L3.500000,7.800000L3.500000,6.600000l2.900000,0.000000L6.400000,9.900000z"/>
+    </group>
 </vector>
diff --git a/packages/SystemUI/res/drawable/ic_qs_signal_h.xml b/packages/SystemUI/res/drawable/ic_qs_signal_h.xml
index d694e61..b9572b2 100644
--- a/packages/SystemUI/res/drawable/ic_qs_signal_h.xml
+++ b/packages/SystemUI/res/drawable/ic_qs_signal_h.xml
@@ -14,11 +14,14 @@
     limitations under the License.
 -->
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="32.0dp"
+        android:width="32dp"
         android:height="32dp"
-        android:viewportWidth="6.0"
-        android:viewportHeight="6.0">
-    <path
-        android:fillColor="#FFFFFFFF"
-        android:pathData="M6.000000,11.000000L4.400000,11.000000L4.400000,7.500000L1.700000,7.500000L1.700000,11.000000L0.000000,11.000000L0.000000,2.500000l1.700000,0.000000l0.000000,3.700000l2.700000,0.000000L4.400000,2.500000L6.000000,2.500000L6.000000,11.000000z"/>
+        android:viewportWidth="13.0"
+        android:viewportHeight="13.0">
+      <group
+        android:translateX="3.5" >
+        <path
+            android:fillColor="#FFFFFFFF"
+            android:pathData="M6.000000,11.000000L4.400000,11.000000L4.400000,7.500000L1.700000,7.500000L1.700000,11.000000L0.000000,11.000000L0.000000,2.500000l1.700000,0.000000l0.000000,3.700000l2.700000,0.000000L4.400000,2.500000L6.000000,2.500000L6.000000,11.000000z"/>
+      </group>
 </vector>
diff --git a/packages/SystemUI/res/layout/battery_percentage_view.xml b/packages/SystemUI/res/layout/battery_percentage_view.xml
index acae9f5..f5c3d40 100644
--- a/packages/SystemUI/res/layout/battery_percentage_view.xml
+++ b/packages/SystemUI/res/layout/battery_percentage_view.xml
@@ -25,5 +25,5 @@
         android:textAppearance="@style/TextAppearance.StatusBar.Expanded.Clock"
         android:textColor="?android:attr/textColorPrimary"
         android:gravity="center_vertical|start"
-        android:paddingStart="4dp"
+        android:paddingStart="@dimen/battery_level_padding_start"
         />
diff --git a/packages/SystemUI/res/layout/keyguard_status_bar.xml b/packages/SystemUI/res/layout/keyguard_status_bar.xml
index a2dfc0d..c5f2f4a 100644
--- a/packages/SystemUI/res/layout/keyguard_status_bar.xml
+++ b/packages/SystemUI/res/layout/keyguard_status_bar.xml
@@ -52,16 +52,6 @@
             >
             <include layout="@layout/system_icons" />
         </FrameLayout>
-        <TextView android:id="@+id/battery_level"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:layout_gravity="center_vertical"
-            android:layout_marginStart="@dimen/header_battery_margin_keyguard"
-            android:paddingEnd="@dimen/battery_level_padding_end"
-            android:textColor="#ffffff"
-            android:visibility="gone"
-            android:textSize="@dimen/battery_level_text_size"
-            android:importantForAccessibility="noHideDescendants"/>
     </LinearLayout>
 
     <com.android.keyguard.CarrierText
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 728dde0..f42344e 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -444,8 +444,8 @@
     <!-- Amount the date/time move when emergency calls only is present -->
     <dimen name="qs_date_time_translation">8dp</dimen>
 
-    <!-- Battery level text padding end when in expanded QS and on Keyguard -->
-    <dimen name="battery_level_padding_end">2dp</dimen>
+    <!-- Padding before battery level text in status bar, QS, and Keyguard -->
+    <dimen name="battery_level_padding_start">4dp</dimen>
 
     <!-- The top padding of the clear all button -->
     <dimen name="clear_all_padding_top">12dp</dimen>
diff --git a/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java b/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java
index bda4c95..ee8641b 100644
--- a/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java
+++ b/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java
@@ -16,7 +16,6 @@
 package com.android.systemui;
 
 import android.content.Context;
-import android.content.res.Configuration;
 import android.content.res.Resources;
 import android.content.res.TypedArray;
 import android.graphics.Rect;
@@ -27,8 +26,6 @@
 import android.net.Uri;
 import android.os.Handler;
 import android.provider.Settings;
-import android.util.ArraySet;
-import android.util.AttributeSet;
 import android.view.Gravity;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -36,7 +33,6 @@
 import android.widget.ImageView;
 import android.widget.LinearLayout;
 
-import android.widget.LinearLayout;
 import android.widget.TextView;
 import com.android.settingslib.graph.BatteryMeterDrawableBase;
 import com.android.systemui.statusbar.phone.StatusBarIconController;
@@ -104,8 +100,8 @@
         updateShowPercent();
     }
 
-    public void forceShowPercent() {
-        mForceShowPercent = true;
+    public void setForceShowPercent(boolean show) {
+        mForceShowPercent = show;
         updateShowPercent();
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java
index 8a60cd1..4e28061 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java
@@ -26,6 +26,7 @@
 import android.app.RemoteAction;
 import android.content.Intent;
 import android.content.pm.ParceledListSlice;
+import android.graphics.Color;
 import android.graphics.PointF;
 import android.os.Bundle;
 import android.os.Handler;
@@ -273,6 +274,7 @@
                     final ImageView actionView = (ImageView) inflater.inflate(
                             R.layout.pip_menu_action, actionsGroup, false);
                     action.getIcon().loadDrawableAsync(this, d -> {
+                        d.setTint(Color.WHITE);
                         actionView.setImageDrawable(d);
                     }, mHandler);
                     actionView.setContentDescription(action.getContentDescription());
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
index ff58e54..42b09df 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
@@ -28,6 +28,7 @@
 import android.widget.RelativeLayout;
 import android.widget.TextView;
 
+import com.android.systemui.BatteryMeterView;
 import com.android.systemui.Dependency;
 import com.android.systemui.Interpolators;
 import com.android.systemui.R;
@@ -39,8 +40,6 @@
 import com.android.systemui.statusbar.policy.UserInfoController.OnUserInfoChangedListener;
 import com.android.systemui.statusbar.policy.UserSwitcherController;
 
-import java.text.NumberFormat;
-
 /**
  * The header group on Keyguard.
  */
@@ -55,7 +54,7 @@
     private View mSystemIconsSuperContainer;
     private MultiUserSwitch mMultiUserSwitch;
     private ImageView mMultiUserAvatar;
-    private TextView mBatteryLevel;
+    private BatteryMeterView mBatteryView;
 
     private BatteryController mBatteryController;
     private KeyguardUserSwitcher mKeyguardUserSwitcher;
@@ -76,8 +75,9 @@
         mSystemIconsContainer = findViewById(R.id.system_icons_container);
         mMultiUserSwitch = (MultiUserSwitch) findViewById(R.id.multi_user_switch);
         mMultiUserAvatar = (ImageView) findViewById(R.id.multi_user_avatar);
-        mBatteryLevel = (TextView) findViewById(R.id.battery_level);
         mCarrierLabel = (TextView) findViewById(R.id.keyguard_carrier_text);
+        mBatteryView = (BatteryMeterView) mSystemIconsContainer.findViewById(R.id.battery);
+
         loadDimens();
         updateUserSwitcher();
         mBatteryController = Dependency.get(BatteryController.class);
@@ -115,17 +115,6 @@
                 R.dimen.status_bar_height);
         mSystemIconsContainer.setLayoutParams(lp);
 
-        lp = (MarginLayoutParams) mBatteryLevel.getLayoutParams();
-        lp.setMarginStart(
-                getResources().getDimensionPixelSize(R.dimen.header_battery_margin_keyguard));
-        mBatteryLevel.setLayoutParams(lp);
-        mBatteryLevel.setPaddingRelative(mBatteryLevel.getPaddingStart(),
-                mBatteryLevel.getPaddingTop(),
-                getResources().getDimensionPixelSize(R.dimen.battery_level_padding_end),
-                mBatteryLevel.getPaddingBottom());
-        mBatteryLevel.setTextSize(TypedValue.COMPLEX_UNIT_PX,
-                getResources().getDimensionPixelSize(R.dimen.battery_level_text_size));
-
         // Respect font size setting.
         mCarrierLabel.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                 getResources().getDimensionPixelSize(
@@ -168,7 +157,7 @@
                 mMultiUserSwitch.setVisibility(View.GONE);
             }
         }
-        mBatteryLevel.setVisibility(mBatteryCharging ? View.VISIBLE : View.GONE);
+        mBatteryView.setForceShowPercent(mBatteryCharging);
     }
 
     private void updateSystemIconsLayoutParams() {
@@ -233,11 +222,8 @@
 
     @Override
     public void onBatteryLevelChanged(int level, boolean pluggedIn, boolean charging) {
-        String percentage = NumberFormat.getPercentInstance().format((double) level / 100.0);
-        mBatteryLevel.setText(percentage);
-        boolean changed = mBatteryCharging != charging;
-        mBatteryCharging = charging;
-        if (changed) {
+        if (mBatteryCharging != charging) {
+            mBatteryCharging = charging;
             updateVisibilities();
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
index ade1b0b..0e7b2f3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
@@ -176,7 +176,7 @@
         cluster.onDarkChanged(new Rect(0, 0, 0, 0), intensity, colorForeground);
 
         BatteryMeterView battery = (BatteryMeterView) findViewById(R.id.battery);
-        battery.forceShowPercent();
+        battery.setForceShowPercent(true);
         int colorSecondary = Utils.getColorAttr(getContext(), android.R.attr.textColorSecondary);
         battery.setRawColors(colorForeground, colorSecondary);
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedController.java
index aa4eaa7..21f9a79 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedController.java
@@ -26,7 +26,9 @@
 
     interface DeviceProvisionedListener {
         default void onDeviceProvisionedChanged() { }
-        default void onUserSwitched() { }
+        default void onUserSwitched() {
+            onUserSetupChanged();
+        }
         default void onUserSetupChanged() { }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedControllerImpl.java
index 528fefe..cfaca0d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedControllerImpl.java
@@ -66,6 +66,8 @@
         if (mListeners.size() == 1) {
             startListening(getCurrentUser());
         }
+        listener.onUserSetupChanged();
+        listener.onDeviceProvisionedChanged();
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
index 03c46e8..91acf04 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
@@ -17,8 +17,11 @@
 
 import android.content.Context;
 import android.content.Intent;
+import android.database.ContentObserver;
 import android.net.NetworkCapabilities;
+import android.os.Handler;
 import android.os.Looper;
+import android.provider.Settings.Global;
 import android.telephony.PhoneStateListener;
 import android.telephony.ServiceState;
 import android.telephony.SignalStrength;
@@ -49,6 +52,7 @@
     private final SubscriptionDefaults mDefaults;
     private final String mNetworkNameDefault;
     private final String mNetworkNameSeparator;
+    private final ContentObserver mObserver;
     @VisibleForTesting
     final PhoneStateListener mPhoneStateListener;
     // Save entire info for logging, we only use the id.
@@ -97,6 +101,12 @@
         mLastState.iconGroup = mCurrentState.iconGroup = mDefaultIcons;
         // Get initial data sim state.
         updateDataSim();
+        mObserver = new ContentObserver(new Handler(receiverLooper)) {
+            @Override
+            public void onChange(boolean selfChange) {
+                updateTelephony();
+            }
+        };
     }
 
     public void setConfiguration(Config config) {
@@ -144,6 +154,11 @@
                         | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE
                         | PhoneStateListener.LISTEN_DATA_ACTIVITY
                         | PhoneStateListener.LISTEN_CARRIER_NETWORK_CHANGE);
+        mContext.getContentResolver().registerContentObserver(Global.getUriFor(Global.MOBILE_DATA),
+                true, mObserver);
+        mContext.getContentResolver().registerContentObserver(Global.getUriFor(
+                Global.MOBILE_DATA + mSubscriptionInfo.getSubscriptionId()),
+                true, mObserver);
     }
 
     /**
@@ -151,6 +166,7 @@
      */
     public void unregisterListener() {
         mPhone.listen(mPhoneStateListener, 0);
+        mContext.getContentResolver().unregisterContentObserver(mObserver);
     }
 
     /**
@@ -242,11 +258,11 @@
             description = mCurrentState.isEmergency ? null : mCurrentState.networkName;
         }
         boolean activityIn = mCurrentState.dataConnected
-                        && !mCurrentState.carrierNetworkChangeMode
-                        && mCurrentState.activityIn;
+                && !mCurrentState.carrierNetworkChangeMode
+                && mCurrentState.activityIn;
         boolean activityOut = mCurrentState.dataConnected
-                        && !mCurrentState.carrierNetworkChangeMode
-                        && mCurrentState.activityOut;
+                && !mCurrentState.carrierNetworkChangeMode
+                && mCurrentState.activityOut;
         showDataIcon &= mCurrentState.isDefault || dataDisabled;
         int typeIcon = showDataIcon ? icons.mDataType : 0;
         callback.setMobileDataIndicators(statusIcon, qsIcon, typeIcon, qsTypeIcon,
@@ -294,7 +310,7 @@
             final int iconMode = mServiceState.getCdmaEriIconMode();
             return mServiceState.getCdmaEriIconIndex() != EriInfo.ROAMING_INDICATOR_OFF
                     && (iconMode == EriInfo.ROAMING_ICON_MODE_NORMAL
-                        || iconMode == EriInfo.ROAMING_ICON_MODE_FLASH);
+                    || iconMode == EriInfo.ROAMING_ICON_MODE_FLASH);
         } else {
             return mServiceState != null && mServiceState.getRoaming();
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java
index eb47a3c..5657560 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java
@@ -43,7 +43,6 @@
 
     void addEmergencyListener(EmergencyListener listener);
     void removeEmergencyListener(EmergencyListener listener);
-    void setUserSetupComplete(boolean userSetup);
     boolean hasEmergencyCryptKeeperText();
     boolean isRadioOn();
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
index d7c919d..a85426c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
@@ -551,17 +551,11 @@
         updateAirplaneMode(true /* force */);
     }
 
-    public void setUserSetupComplete(final boolean userSetup) {
-        mReceiverHandler.post(new Runnable() {
-            @Override
-            public void run() {
-                handleSetUserSetupComplete(userSetup);
-            }
-        });
+    private void setUserSetupComplete(final boolean userSetup) {
+        mReceiverHandler.post(() -> handleSetUserSetupComplete(userSetup));
     }
 
-    @VisibleForTesting
-    void handleSetUserSetupComplete(boolean userSetup) {
+    private void handleSetUserSetupComplete(boolean userSetup) {
         mUserSetup = userSetup;
         for (MobileSignalController controller : mMobileSignalControllers.values()) {
             controller.setUserSetupComplete(mUserSetup);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerBaseTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerBaseTest.java
index 0e5f513..19b4b17 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerBaseTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerBaseTest.java
@@ -31,6 +31,7 @@
 import android.util.Log;
 import com.android.internal.telephony.cdma.EriInfo;
 import com.android.settingslib.net.DataUsageController;
+import com.android.systemui.statusbar.policy.DeviceProvisionedController.DeviceProvisionedListener;
 import com.android.systemui.statusbar.policy.NetworkController.IconState;
 import com.android.systemui.statusbar.policy.NetworkController.SignalCallback;
 import com.android.systemui.statusbar.policy.NetworkControllerImpl.Config;
@@ -43,6 +44,8 @@
 import org.junit.runner.Description;
 import org.mockito.ArgumentCaptor;
 import org.mockito.Mockito;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
 
 import java.io.PrintWriter;
 import java.io.StringWriter;
@@ -56,6 +59,7 @@
 import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.anyString;
 import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -82,6 +86,8 @@
     protected CallbackHandler mCallbackHandler;
     protected SubscriptionDefaults mMockSubDefaults;
     protected NetworkScoreManager mMockNetworkScoreManager;
+    protected DeviceProvisionedController mMockProvisionController;
+    protected DeviceProvisionedListener mUserCallback;
 
     protected int mSubId;
 
@@ -120,11 +126,21 @@
         mConfig = new Config();
         mConfig.hspaDataDistinguishable = true;
         mCallbackHandler = mock(CallbackHandler.class);
+
+        mMockProvisionController = mock(DeviceProvisionedController.class);
+        when(mMockProvisionController.isUserSetup(anyInt())).thenReturn(true);
+        doAnswer(invocation -> {
+            mUserCallback = (DeviceProvisionedListener) invocation.getArguments()[0];
+            mUserCallback.onUserSetupChanged();
+            mUserCallback.onDeviceProvisionedChanged();
+            return null;
+        }).when(mMockProvisionController).addCallback(any());
+
         mNetworkController = new NetworkControllerImpl(mContext, mMockCm, mMockNetworkScoreManager,
                 mMockTm, mMockWm, mMockSm,
                 mConfig, Looper.getMainLooper(), mCallbackHandler,
                 mock(AccessPointControllerImpl.class), mock(DataUsageController.class),
-                mMockSubDefaults, mock(DeviceProvisionedController.class));
+                mMockSubDefaults, mMockProvisionController);
         setupNetworkController();
 
         // Trigger blank callbacks to always get the current state (some tests don't trigger
@@ -139,7 +155,6 @@
         when(mMockTm.getDataEnabled(mSubId)).thenReturn(true);
         setDefaultSubId(mSubId);
         setSubscriptions(mSubId);
-        mNetworkController.handleSetUserSetupComplete(true);
         mMobileSignalController = mNetworkController.mMobileSignalControllers.get(mSubId);
         mPhoneStateListener = mMobileSignalController.mPhoneStateListener;
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerDataTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerDataTest.java
index d7f961c..ba20999 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerDataTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerDataTest.java
@@ -1,16 +1,19 @@
 package com.android.systemui.statusbar.policy;
 
+import static org.mockito.Matchers.anyInt;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 
 import android.net.NetworkCapabilities;
 import android.os.Looper;
 import android.support.test.runner.AndroidJUnit4;
 import android.telephony.TelephonyManager;
 import android.test.suitebuilder.annotation.SmallTest;
+
 import com.android.settingslib.net.DataUsageController;
+
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.mockito.Mockito;
 
 @SmallTest
 @RunWith(AndroidJUnit4.class)
@@ -106,7 +109,7 @@
     @Test
     public void testDataDisabledIcon() {
         setupNetworkController();
-        Mockito.when(mMockTm.getDataEnabled(mSubId)).thenReturn(false);
+        when(mMockTm.getDataEnabled(mSubId)).thenReturn(false);
         setupDefaultSignal();
         updateDataConnectionState(TelephonyManager.DATA_DISCONNECTED, 0);
         setConnectivity(NetworkCapabilities.TRANSPORT_CELLULAR, false, false);
@@ -118,11 +121,12 @@
     @Test
     public void testDataDisabledIcon_UserNotSetup() {
         setupNetworkController();
-        Mockito.when(mMockTm.getDataEnabled(mSubId)).thenReturn(false);
+        when(mMockTm.getDataEnabled(mSubId)).thenReturn(false);
         setupDefaultSignal();
         updateDataConnectionState(TelephonyManager.DATA_DISCONNECTED, 0);
         setConnectivity(NetworkCapabilities.TRANSPORT_CELLULAR, false, false);
-        mNetworkController.handleSetUserSetupComplete(false);
+        when(mMockProvisionController.isUserSetup(anyInt())).thenReturn(false);
+        mUserCallback.onUserSetupChanged();
 
         // Don't show the X until the device is setup.
         verifyDataIndicators(0, 0);
@@ -154,7 +158,7 @@
         verifyDataIndicators(TelephonyIcons.DATA_LTE[1][0 /* No direction */],
                 TelephonyIcons.QS_DATA_LTE);
 
-        Mockito.when(mServiceState.getDataNetworkType())
+        when(mServiceState.getDataNetworkType())
                 .thenReturn(TelephonyManager.NETWORK_TYPE_HSPA);
         updateServiceState();
         verifyDataIndicators(TelephonyIcons.DATA_H[1][0 /* No direction */],
diff --git a/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeNetworkController.java b/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeNetworkController.java
index 5497686..47ed5ca 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeNetworkController.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeNetworkController.java
@@ -47,11 +47,6 @@
     }
 
     @Override
-    public void setUserSetupComplete(boolean userSetup) {
-
-    }
-
-    @Override
     public boolean hasEmergencyCryptKeeperText() {
         return false;
     }
diff --git a/proto/src/metrics_constants.proto b/proto/src/metrics_constants.proto
index c81bd1b..c7f518c 100644
--- a/proto/src/metrics_constants.proto
+++ b/proto/src/metrics_constants.proto
@@ -3458,6 +3458,14 @@
     // OPEN: Settings > Apps > Default Apps > Assist >  Default voice input
     DEFAULT_VOICE_INPUT_PICKER = 844;
 
+    // OPEN: Settings > Storage > [Profile]
+    SETTINGS_STORAGE_PROFILE = 845;
+
+    // OPEN: Settings > Security & screen lock -> Encryption & crendentials
+    // CATEGORY: SETTINGS
+    // OS: O
+    ENCRYPTION_AND_CREDENTIAL = 846;
+
     // ---- 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/AnchoredWindow.java b/services/autofill/java/com/android/server/autofill/AnchoredWindow.java
deleted file mode 100644
index 64c6abd..0000000
--- a/services/autofill/java/com/android/server/autofill/AnchoredWindow.java
+++ /dev/null
@@ -1,292 +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.server.autofill;
-
-import static com.android.server.autofill.Helper.DEBUG;
-
-import android.annotation.Nullable;
-import android.content.Context;
-import android.graphics.PixelFormat;
-import android.graphics.Rect;
-import android.os.IBinder;
-import android.util.Slog;
-import android.view.Gravity;
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.View.MeasureSpec;
-import android.view.WindowManager;
-import android.view.WindowManager.LayoutParams;
-import android.widget.FrameLayout;
-
-/**
- * A window above the application that is smartly anchored to a rectangular region.
- */
-final class AnchoredWindow implements View.OnLayoutChangeListener, View.OnTouchListener {
-    private static final String TAG = "AutoFill";
-
-    private static final int NULL_HEIGHT = -1;
-
-    private final WindowManager mWm;
-    private final IBinder mAppToken;
-    private final View mContentView;
-
-    private final View mWindowSizeListenerView;
-    private final int mMinMargin;
-
-    private int mLastHeight = NULL_HEIGHT;
-    @Nullable
-    private Rect mLastBounds;
-    @Nullable
-    private Rect mLastDisplayBounds;
-
-    /**
-     * Constructor.
-     *
-     * @param wm window manager that draws the content on a window
-     * @param appToken token to pass to window manager
-     * @param contentView content of the window
-     */
-    AnchoredWindow(WindowManager wm, IBinder appToken, View contentView) {
-        mWm = wm;
-        mAppToken = appToken;
-        mContentView = contentView;
-
-        mContentView.addOnLayoutChangeListener(this);
-
-        Context context = contentView.getContext();
-
-        mWindowSizeListenerView = new FrameLayout(context);
-        mWindowSizeListenerView.addOnLayoutChangeListener(this);
-
-        mMinMargin = context.getResources().getDimensionPixelSize(
-                com.android.internal.R.dimen.autofill_fill_min_margin);
-    }
-
-    /**
-     * Shows the window.
-     *
-     * @param bounds the region the window should be anchored to
-     */
-    void show(Rect bounds) {
-        if (DEBUG) Slog.d(TAG, "show bounds=" + bounds);
-
-        if (!mWindowSizeListenerView.isAttachedToWindow()) {
-            if (DEBUG) Slog.d(TAG, "adding mWindowSizeListenerView");
-            LayoutParams params = createWindowLayoutParams(
-                    mAppToken,
-                    LayoutParams.FLAG_NOT_TOUCHABLE); // not touchable
-            params.gravity = Gravity.LEFT | Gravity.TOP;
-            params.x = 0;
-            params.y = 0;
-            params.width = LayoutParams.MATCH_PARENT;
-            params.height = LayoutParams.MATCH_PARENT;
-            mWm.addView(mWindowSizeListenerView, params);
-        }
-
-        updateBounds(bounds);
-    }
-
-    /**
-     * Hides the window.
-     */
-    void hide() {
-        if (DEBUG) Slog.d(TAG, "hide");
-
-        mLastHeight = NULL_HEIGHT;
-        mLastBounds = null;
-        mLastDisplayBounds = null;
-
-        if (mWindowSizeListenerView.isAttachedToWindow()) {
-            if (DEBUG) Slog.d(TAG, "removing mWindowSizeListenerView");
-            mWm.removeView(mWindowSizeListenerView);
-        }
-
-        if (mContentView.isAttachedToWindow()) {
-            if (DEBUG) Slog.d(TAG, "removing mContentView");
-            mContentView.setOnTouchListener(null);
-            mWm.removeView(mContentView);
-        }
-    }
-
-    @Override
-    public void onLayoutChange(View view, int left, int top, int right, int bottom,
-            int oldLeft, int oldTop, int oldRight, int oldBottom) {
-        if (view == mWindowSizeListenerView) {
-            if (DEBUG) Slog.d(TAG, "onLayoutChange() for mWindowSizeListenerView");
-            // mWindowSizeListenerView layout changed, get the size of the display bounds and updateLocked
-            // the window.
-            final Rect displayBounds = new Rect();
-            view.getBoundsOnScreen(displayBounds);
-            updateDisplayBounds(displayBounds);
-        } else if (view == mContentView) {
-            // mContentView layout changed, updateLocked the window in case its height changed.
-            if (DEBUG) Slog.d(TAG, "onLayoutChange() for mContentView");
-            updateHeight();
-        }
-    }
-
-    // When the window is touched outside, hide the window.
-    @Override
-    public boolean onTouch(View view, MotionEvent event) {
-        if (view == mContentView && event.getAction() == MotionEvent.ACTION_OUTSIDE) {
-            hide();
-            return true;
-        }
-        return false;
-    }
-
-    private boolean updateHeight() {
-        final Rect displayBounds = mLastDisplayBounds;
-        if (displayBounds == null) {
-            return false;
-        }
-
-        mContentView.measure(
-                MeasureSpec.makeMeasureSpec(displayBounds.width(), MeasureSpec.AT_MOST),
-                MeasureSpec.makeMeasureSpec(displayBounds.height(), MeasureSpec.AT_MOST));
-        int height = mContentView.getMeasuredHeight();
-        if (height != mLastHeight) {
-            if (DEBUG) Slog.d(TAG, "updateLocked height=" + height);
-            mLastHeight = height;
-            update(height, mLastBounds, displayBounds);
-            return true;
-        } else {
-            return false;
-        }
-    }
-
-    private void updateBounds(Rect bounds) {
-        if (!bounds.equals(mLastBounds)) {
-            if (DEBUG) Slog.d(TAG, "updateLocked bounds=" + bounds);
-            mLastBounds = bounds;
-
-            update(mLastHeight, bounds, mLastDisplayBounds);
-        }
-    }
-
-    private void updateDisplayBounds(Rect displayBounds) {
-        if (!displayBounds.equals(mLastDisplayBounds)) {
-            if (DEBUG) Slog.d(TAG, "updateLocked displayBounds=" + displayBounds);
-            mLastDisplayBounds = displayBounds;
-
-            if (!updateHeight()) {
-                update(mLastHeight, mLastBounds, displayBounds);
-            }
-        }
-    }
-
-    // Updates the window if height, bounds, and displayBounds are not null.
-    // Caller should ensure that something changed before calling.
-    private void update(int height, @Nullable Rect bounds, @Nullable Rect displayBounds) {
-        if (height == NULL_HEIGHT || bounds == null || displayBounds == null) {
-            return;
-        }
-
-        if (DEBUG) Slog.d(TAG, "updateLocked height=" + height + ", bounds=" + bounds
-                + ", displayBounds=" + displayBounds);
-
-        final LayoutParams params = createWindowLayoutParams(mAppToken,
-                LayoutParams.FLAG_NOT_TOUCH_MODAL // outside touches go to windows behind us
-                | LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH); // outside touches trigger MotionEvent
-        params.setTitle("AutoFill Fill"); // used for debugging
-        updatePosition(params, height, mMinMargin, bounds, displayBounds);
-        if (!mContentView.isAttachedToWindow()) {
-            if (DEBUG) Slog.d(TAG, "adding mContentView");
-            mWm.addView(mContentView, params);
-            mContentView.setOnTouchListener(this);
-        } else {
-            if (DEBUG) Slog.d(TAG, "updating mContentView");
-            mWm.updateViewLayout(mContentView, params);
-        }
-    }
-
-    /**
-     * Updates the position of the window by altering the {@link LayoutParams}.
-     *
-     * <p>The window can be anchored either above or below the bounds. Anchoring the window below
-     * the bounds is preferred, if it fits. Otherwise, anchor the window on the side with more
-     * space.
-     *
-     * @param params the params to updateLocked
-     * @param height the requested height of the window
-     * @param minMargin the minimum margin between the window and the display bounds
-     * @param bounds the region the window should be anchored to
-     * @param displayBounds the region in which the window may be displayed
-     */
-    private static void updatePosition(
-            LayoutParams params,
-            int height,
-            int minMargin,
-            Rect bounds,
-            Rect displayBounds) {
-        boolean below;
-        int verticalSpace;
-        final int verticalSpaceBelow = displayBounds.bottom - bounds.bottom - minMargin;
-        if (height <= verticalSpaceBelow) {
-            // Fits below bounds.
-            below = true;
-            verticalSpace = height;
-        } else {
-            final int verticalSpaceAbove = bounds.top - displayBounds.top - minMargin;
-            if (height <= verticalSpaceAbove) {
-                // Fits above bounds.
-                below = false;
-                verticalSpace = height;
-            } else {
-                // Pick above/below based on which has the most space.
-                if (verticalSpaceBelow >= verticalSpaceAbove) {
-                    below = true;
-                    verticalSpace = verticalSpaceBelow;
-                } else {
-                    below = false;
-                    verticalSpace = verticalSpaceAbove;
-                }
-            }
-        }
-
-        int gravity;
-        int y;
-        if (below) {
-            if (DEBUG) Slog.d(TAG, "anchorBelow");
-            gravity = Gravity.TOP | Gravity.LEFT;
-            y = bounds.bottom - displayBounds.top;
-        } else {
-            if (DEBUG) Slog.d(TAG, "anchorAbove");
-            gravity = Gravity.BOTTOM | Gravity.LEFT;
-            y = displayBounds.bottom - bounds.top;
-        }
-
-        final int x = bounds.left - displayBounds.left;
-
-        params.gravity = gravity;
-        params.x = x;
-        params.y = y;
-        params.width = bounds.width();
-        params.height = verticalSpace;
-    }
-
-    private static LayoutParams createWindowLayoutParams(IBinder appToken, int flags) {
-        final LayoutParams params = new LayoutParams();
-        params.token = appToken;
-        params.type = LayoutParams.TYPE_PHONE;
-        params.flags =
-                flags
-                | LayoutParams.FLAG_NOT_FOCUSABLE // don't receive input events
-                | LayoutParams.FLAG_ALT_FOCUSABLE_IM; // resize for soft input
-        params.format = PixelFormat.TRANSLUCENT;
-        return params;
-    }
-}
diff --git a/services/autofill/java/com/android/server/autofill/AutoFillManagerService.java b/services/autofill/java/com/android/server/autofill/AutoFillManagerService.java
index 3257812..520b43a 100644
--- a/services/autofill/java/com/android/server/autofill/AutoFillManagerService.java
+++ b/services/autofill/java/com/android/server/autofill/AutoFillManagerService.java
@@ -57,6 +57,7 @@
 import com.android.server.FgThread;
 import com.android.server.LocalServices;
 import com.android.server.SystemService;
+import com.android.server.autofill.ui.AutoFillUI;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
@@ -271,8 +272,8 @@
         }
 
         @Override
-        public void startSession(IBinder activityToken, IBinder appCallback, AutoFillId autoFillId,
-                Rect bounds, AutoFillValue value, int userId) {
+        public void startSession(IBinder activityToken, IBinder windowToken, IBinder appCallback,
+                AutoFillId autoFillId, Rect bounds, AutoFillValue value, int userId) {
             // TODO(b/33197203): make sure it's called by resumed / focused activity
 
             if (VERBOSE) {
@@ -282,7 +283,8 @@
 
             synchronized (mLock) {
                 final AutoFillManagerServiceImpl service = getServiceForUserLocked(userId);
-                service.startSessionLocked(activityToken, appCallback, autoFillId, bounds, value);
+                service.startSessionLocked(activityToken, windowToken, appCallback,
+                        autoFillId, bounds, value);
             }
         }
 
diff --git a/services/autofill/java/com/android/server/autofill/AutoFillManagerServiceImpl.java b/services/autofill/java/com/android/server/autofill/AutoFillManagerServiceImpl.java
index 55e00ed..f399f59 100644
--- a/services/autofill/java/com/android/server/autofill/AutoFillManagerServiceImpl.java
+++ b/services/autofill/java/com/android/server/autofill/AutoFillManagerServiceImpl.java
@@ -70,6 +70,7 @@
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.os.HandlerCaller;
 import com.android.internal.os.IResultReceiver;
+import com.android.server.autofill.ui.AutoFillUI;
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
@@ -272,8 +273,8 @@
         }
     }
 
-    void startSessionLocked(IBinder activityToken, IBinder appCallbackToken, AutoFillId autoFillId,
-            Rect bounds, AutoFillValue value) {
+    void startSessionLocked(IBinder activityToken, IBinder windowToken, IBinder appCallbackToken,
+            AutoFillId autoFillId,  Rect bounds, AutoFillValue value) {
         if (!hasService()) {
             return;
         }
@@ -290,7 +291,8 @@
             return;
         }
 
-        final Session newSession = createSessionByTokenLocked(activityToken, appCallbackToken);
+        final Session newSession = createSessionByTokenLocked(activityToken,
+                windowToken, appCallbackToken);
         newSession.updateLocked(autoFillId, bounds, value, FLAG_START_SESSION);
     }
 
@@ -308,8 +310,10 @@
         session.showSaveLocked();
     }
 
-    private Session createSessionByTokenLocked(IBinder activityToken, IBinder appCallbackToken) {
-        final Session newSession = new Session(mContext, activityToken, appCallbackToken);
+    private Session createSessionByTokenLocked(IBinder activityToken, IBinder windowToken,
+            IBinder appCallbackToken) {
+        final Session newSession = new Session(mContext, activityToken,
+                windowToken, appCallbackToken);
         mSessions.put(activityToken, newSession);
 
         /*
@@ -556,6 +560,7 @@
     final class Session implements RemoteFillService.FillServiceCallbacks, ViewState.Listener,
             AutoFillUI.AutoFillUiCallback {
         private final IBinder mActivityToken;
+        private final IBinder mWindowToken;
 
         @GuardedBy("mLock")
         private final Map<AutoFillId, ViewState> mViewStates = new ArrayMap<>();
@@ -587,10 +592,12 @@
         @GuardedBy("mLock")
         private AssistStructure mStructure;
 
-        private Session(Context context, IBinder activityToken, IBinder client) {
+        private Session(Context context, IBinder activityToken, IBinder windowToken,
+                IBinder client) {
             mRemoteFillService = new RemoteFillService(context,
                     mInfo.getServiceInfo().getComponentName(), mUserId, this);
             mActivityToken = activityToken;
+            mWindowToken = windowToken;
 
             mClient = IAutoFillManagerClient.Stub.asInterface(client);
             try {
@@ -662,7 +669,9 @@
         // AutoFillUiCallback
         @Override
         public void fill(Dataset dataset) {
-            autoFill(dataset);
+            mHandlerCaller.getHandler().post(() -> {
+                autoFill(dataset);
+            });
         }
 
         // AutoFillUiCallback
@@ -726,7 +735,8 @@
                         Slog.d(TAG, "finishSessionLocked(): found a change on " + id + ": "
                                 + state.mAutoFillValue);
                     }
-                    mUi.showSaveUi();
+                    getUiForShowing().showSaveUi(mInfo.getServiceInfo()
+                            .loadLabel(mContext.getPackageManager()));
                     return;
                 }
             }
@@ -810,8 +820,9 @@
                     viewState.mAutoFillValue = value;
 
                     // Update the chooser UI
-                    mUi.updateFillUi(value.coerceToString());
+                    getUiForShowing().filterFillUi(value.coerceToString());
                 }
+
                 return;
             }
 
@@ -955,7 +966,7 @@
 
         private AutoFillUI getUiForShowing() {
             synchronized (mLock) {
-                mUi.setCallbackLocked(this, mActivityToken);
+                mUi.setCallback(this, mWindowToken);
                 return mUi;
             }
         }
@@ -995,7 +1006,7 @@
 
         private void destroyLocked() {
             mRemoteFillService.destroy();
-            mUi.setCallbackLocked(null, null);
+            mUi.setCallback(null, null);
         }
 
         private void removeSelf() {
diff --git a/services/autofill/java/com/android/server/autofill/AutoFillUI.java b/services/autofill/java/com/android/server/autofill/AutoFillUI.java
deleted file mode 100644
index 78dd247..0000000
--- a/services/autofill/java/com/android/server/autofill/AutoFillUI.java
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.server.autofill;
-
-import static com.android.server.autofill.Helper.DEBUG;
-
-import android.annotation.Nullable;
-import android.content.Context;
-import android.content.IntentSender;
-import android.graphics.Rect;
-import android.os.Handler;
-import android.os.IBinder;
-import android.service.autofill.Dataset;
-import android.service.autofill.FillResponse;
-import android.text.format.DateUtils;
-import android.util.Slog;
-import android.view.Gravity;
-import android.view.View;
-import android.view.WindowManager;
-import android.view.WindowManager.LayoutParams;
-import android.view.autofill.AutoFillId;
-import android.widget.Toast;
-
-import com.android.server.UiThread;
-
-import java.io.PrintWriter;
-
-/**
- * Handles all auto-fill related UI tasks.
- */
-// TODO(b/33197203): document exactly what once the auto-fill bar is implemented
-final class AutoFillUI {
-    private static final String TAG = "AutoFillUI";
-
-    private static final long SNACK_BAR_LIFETIME_MS = 5 * DateUtils.SECOND_IN_MILLIS;
-
-    private static final int MSG_HIDE_SNACK_BAR = 1;
-
-    private final Handler mHandler = UiThread.getHandler();
-
-    private final Context mContext;
-
-    private final WindowManager mWm;
-
-    private AnchoredWindow mFillWindow;
-
-    private DatasetPicker mDatasetPicker;
-
-    private AutoFillUiCallback mCallback;
-
-    private IBinder mActivityToken;
-
-    /**
-     * Custom snackbar UI used for saving autofill or other informational messages.
-     */
-    private View mSnackbar;
-
-    AutoFillUI(Context context) {
-        mContext = context;
-        mWm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
-    }
-
-    void setCallbackLocked(AutoFillUiCallback callback, IBinder activityToken) {
-        mHandler.post(() -> {
-            hideAllUiThread();
-            mCallback = callback;
-            mActivityToken = activityToken;
-        });
-    }
-
-    /**
-     * Displays an error message to the user.
-     */
-    void showError(CharSequence message) {
-        // TODO(b/33197203): proper implementation
-        UiThread.getHandler().post(() -> {
-            if (!hasCallback()) {
-                return;
-            }
-            hideAllUiThread();
-            Toast.makeText(mContext, "AutoFill error: " + message, Toast.LENGTH_LONG).show();
-        });
-    }
-
-    /**
-     * Hides the fill UI.
-     */
-    void hideFillUi() {
-        mHandler.post(() -> hideFillUiUiThread());
-    }
-
-    @android.annotation.UiThread
-    private void hideFillUiUiThread() {
-        if (mFillWindow != null) {
-            if (DEBUG) Slog.d(TAG, "hideFillUiUiThread(): hide" + mFillWindow);
-            mFillWindow.hide();
-        }
-        mFillWindow = null;
-        mDatasetPicker = null;
-    }
-
-    void updateFillUi(@Nullable String filterText) {
-        mHandler.post(() -> {
-            if (!hasCallback()) {
-                return;
-            }
-            hideSnackbarUiThread();
-            if (mDatasetPicker != null) {
-                mDatasetPicker.update(filterText);
-            }
-        });
-    }
-
-    /**
-     * Shows the fill UI, removing the previous fill UI if the has changed.
-     *
-     * @param focusedId the currently focused field
-     * @param response the current fill response
-     * @param bounds bounds of the view to be filled, used if changed
-     * @param filterText text of the view to be filled, used if changed
-     */
-    void showFillUi(AutoFillId focusedId, @Nullable FillResponse response, Rect bounds,
-            String filterText) {
-        mHandler.post(() -> {
-            if (!hasCallback()) {
-                return;
-            }
-            hideSnackbarUiThread();
-            final View content;
-            if (response.getPresentation() != null) {
-                content = response.getPresentation().apply(mContext, null);
-                content.setOnClickListener((view) -> {
-                    if (mCallback != null) {
-                        mCallback.authenticate(response.getAuthentication());
-                    }
-                    hideFillUiUiThread();
-                });
-            } else {
-                mDatasetPicker = new DatasetPicker(mContext, response.getDatasets(),
-                        focusedId, new DatasetPicker.Listener() {
-                    @Override
-                    public void onDatasetPicked(Dataset dataset) {
-                        if (mCallback != null) {
-                            mCallback.fill(dataset);
-                        }
-                        hideFillUiUiThread();
-                    }
-
-                    @Override
-                    public void onCanceled() {
-                        hideFillUiUiThread();
-                    }
-                });
-                mDatasetPicker.update(filterText);
-                content = mDatasetPicker;
-            }
-
-            mFillWindow = new AnchoredWindow(mWm, mActivityToken, content);
-            mFillWindow.show(bounds);
-        });
-    }
-
-    /**
-     * Shows the UI asking the user to save for auto-fill.
-     */
-    void showSaveUi() {
-        mHandler.post(() -> {
-            if (!hasCallback()) {
-                return;
-            }
-            hideAllUiThread();
-            showSnackbarUiThread(new SavePrompt(mContext,
-                    new SavePrompt.OnSaveListener() {
-                @Override
-                public void onSaveClick() {
-                    hideSnackbarUiThread();
-                    // TODO(b/33197203): add MetricsLogger call
-                    mCallback.save();
-                }
-
-                @Override
-                public void onCancelClick() {
-                    // TODO(b/33197203): add MetricsLogger call
-                    hideSnackbarUiThread();
-                }
-            }));
-        });
-    }
-
-    /**
-     * Hides all UI affordances.
-     */
-    void hideAll() {
-        mHandler.post(() -> hideAllUiThread());
-    }
-
-    @android.annotation.UiThread
-    private void hideAllUiThread() {
-        hideSnackbarUiThread();
-        hideFillUiUiThread();
-    }
-
-    void dump(PrintWriter pw) {
-        pw.println("AufoFill UI");
-        final String prefix = "  ";
-        pw.print(prefix); pw.print("mActivityToken: "); pw.println(mActivityToken);
-        pw.print(prefix); pw.print("mSnackBar: "); pw.println(mSnackbar);
-    }
-
-    //similar to a snackbar, but can be a bit custom since it is more than just text. This will
-    //allow two buttons for saving or not saving the autofill for instance as well.
-    @android.annotation.UiThread
-    private void showSnackbarUiThread(View snackBar) {
-        final LayoutParams params = new LayoutParams();
-        params.type = LayoutParams.TYPE_PHONE; // TODO(b/33197203) use app window token
-        params.flags =
-                LayoutParams.FLAG_NOT_FOCUSABLE // don't receive input events,
-                | LayoutParams.FLAG_ALT_FOCUSABLE_IM // resize for soft input
-                | LayoutParams.FLAG_NOT_TOUCH_MODAL; // outside touches go to windows behind us
-        params.softInputMode =
-                LayoutParams.SOFT_INPUT_ADJUST_PAN; // pan with soft input
-        params.gravity = Gravity.BOTTOM | Gravity.START;
-        params.width = LayoutParams.MATCH_PARENT;
-        params.height = LayoutParams.WRAP_CONTENT;
-
-        mHandler.post(() -> {
-            mSnackbar = snackBar;
-            mWm.addView(mSnackbar, params);
-        });
-
-        if (DEBUG) {
-            Slog.d(TAG, "showSnackbar(): auto dismissing it in " + SNACK_BAR_LIFETIME_MS + " ms");
-        }
-        mHandler.sendMessageDelayed(mHandler
-                        .obtainMessage(MSG_HIDE_SNACK_BAR), SNACK_BAR_LIFETIME_MS);
-    }
-
-    @android.annotation.UiThread
-    private void hideSnackbarUiThread() {
-        mHandler.removeMessages(MSG_HIDE_SNACK_BAR);
-        if (mSnackbar != null) {
-            mWm.removeView(mSnackbar);
-            mSnackbar = null;
-        }
-    }
-
-    private boolean hasCallback() {
-        return mCallback != null;
-    }
-
-    interface AutoFillUiCallback {
-        void authenticate(IntentSender intent);
-        void fill(Dataset dataset);
-        void save();
-    }
-}
diff --git a/services/autofill/java/com/android/server/autofill/DatasetPicker.java b/services/autofill/java/com/android/server/autofill/DatasetPicker.java
deleted file mode 100644
index e25f2ce..0000000
--- a/services/autofill/java/com/android/server/autofill/DatasetPicker.java
+++ /dev/null
@@ -1,115 +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.server.autofill;
-
-import android.content.Context;
-import android.service.autofill.Dataset;
-import android.util.ArraySet;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.autofill.AutoFillId;
-import android.view.autofill.AutoFillValue;
-import android.widget.AdapterView;
-import android.widget.AdapterView.OnItemClickListener;
-import android.widget.ArrayAdapter;
-import android.widget.FrameLayout;
-import android.widget.ListView;
-import android.widget.RemoteViews;
-import com.android.internal.R;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * This class manages the dataset selection UI.
- */
-final class DatasetPicker extends FrameLayout implements OnItemClickListener {
-    interface Listener {
-        void onDatasetPicked(Dataset dataset);
-        void onCanceled();
-    }
-
-    private final Listener mListener;
-
-    private final ArrayAdapter<ViewItem> mAdapter;
-
-    DatasetPicker(Context context, ArrayList<Dataset> datasets, AutoFillId filteredViewId,
-            Listener listener) {
-        super(context);
-        mListener = listener;
-
-        final List<ViewItem> items = new ArrayList<>(datasets.size());
-        for (Dataset dataset : datasets) {
-            final int index = dataset.getFieldIds().indexOf(filteredViewId);
-            if (index >= 0) {
-                AutoFillValue value = dataset.getFieldValues().get(index);
-                items.add(new ViewItem(dataset, value.coerceToString()));
-            }
-        }
-
-        mAdapter = new ArrayAdapter<ViewItem>(context, 0, items) {
-            @Override
-            public View getView(int position, View convertView, ViewGroup parent) {
-                RemoteViews presentation = getItem(position).getDataset().getPresentation();
-                return presentation.apply(context, parent);
-            }
-        };
-
-        LayoutInflater inflater = LayoutInflater.from(context);
-        ListView content = (ListView) inflater.inflate(
-                com.android.internal.R.layout.autofill_dataset_picker, this, true)
-                .findViewById(com.android.internal.R.id.list);
-        content.setAdapter(mAdapter);
-        content.setOnItemClickListener(this);
-    }
-
-    public void update(String prefix) {
-        mAdapter.getFilter().filter(prefix, (count) -> {
-            if (count <= 0 && mListener != null) {
-                mListener.onCanceled();
-            }
-        });
-    }
-
-    @Override
-    public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {
-        if (mListener != null) {
-            final ViewItem vi = (ViewItem) adapterView.getItemAtPosition(pos);
-            mListener.onDatasetPicked(vi.getDataset());
-        }
-    }
-
-    private static class ViewItem {
-        private final String mValue;
-        private final Dataset mDataset;
-
-        ViewItem(Dataset dataset, String value) {
-            mDataset = dataset;
-            mValue = value;
-        }
-
-        public Dataset getDataset() {
-            return mDataset;
-        }
-
-        @Override
-        public String toString() {
-            // used by ArrayAdapter
-            return mValue;
-        }
-    }
-}
diff --git a/services/autofill/java/com/android/server/autofill/SavePrompt.java b/services/autofill/java/com/android/server/autofill/SavePrompt.java
deleted file mode 100644
index 85c6d7d..0000000
--- a/services/autofill/java/com/android/server/autofill/SavePrompt.java
+++ /dev/null
@@ -1,57 +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.server.autofill;
-
-import android.content.Context;
-import android.widget.RelativeLayout;
-import android.widget.TextView;
-import android.view.LayoutInflater;
-import android.view.View;
-
-import com.android.internal.R;
-
-/**
- * Autofill Save Prompt
- */
-final class SavePrompt extends RelativeLayout {
-    public interface OnSaveListener {
-        void onSaveClick();
-        void onCancelClick();
-    }
-
-    private final TextView mNoButton;
-    private final TextView mYesButton;
-    private final OnSaveListener mListener;
-
-    SavePrompt(Context context, OnSaveListener listener) {
-        super(context);
-        mListener = listener;
-        LayoutInflater inflater = LayoutInflater.from(context);
-        View view = inflater.inflate(R.layout.autofill_save, this);
-
-        mNoButton = (TextView) view.findViewById(R.id.autofill_save_no);
-        mNoButton.setOnClickListener((v) -> {
-            mListener.onCancelClick();
-        });
-
-        mYesButton = (TextView) view.findViewById(R.id.autofill_save_yes);
-        mYesButton.setOnClickListener((v) -> {
-            mListener.onSaveClick();
-        });
-
-    }
-}
diff --git a/services/autofill/java/com/android/server/autofill/ui/AutoFillUI.java b/services/autofill/java/com/android/server/autofill/ui/AutoFillUI.java
new file mode 100644
index 0000000..cc0baa3
--- /dev/null
+++ b/services/autofill/java/com/android/server/autofill/ui/AutoFillUI.java
@@ -0,0 +1,240 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.server.autofill.ui;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.Context;
+import android.content.IntentSender;
+import android.graphics.Rect;
+import android.os.Handler;
+import android.os.IBinder;
+import android.service.autofill.Dataset;
+import android.service.autofill.FillResponse;
+import android.text.TextUtils;
+import android.view.autofill.AutoFillId;
+import android.widget.Toast;
+
+import com.android.server.UiThread;
+
+import java.io.PrintWriter;
+
+/**
+ * Handles all auto-fill related UI tasks. The UI has two components:
+ * fill UI that shows a popup style window anchored at the focused
+ * input field for choosing a dataset to fill or trigger the response
+ * authentication flow; save UI that shows a toast style window for
+ * managing saving of user edits.
+ */
+public final class AutoFillUI {
+    private final Handler mHandler = UiThread.getHandler();
+    private final @NonNull Context mContext;
+
+    private @Nullable FillUi mFillUi;
+    private @Nullable SaveUi mSaveUi;
+
+    private @Nullable AutoFillUiCallback mCallback;
+    private @Nullable IBinder mWindowToken;
+
+    public interface AutoFillUiCallback {
+        void authenticate(@NonNull IntentSender intent);
+        void fill(@NonNull Dataset dataset);
+        void save();
+    }
+
+    public AutoFillUI(@NonNull Context context) {
+        mContext = context;
+    }
+
+    public void setCallback(@Nullable AutoFillUiCallback callback,
+            @Nullable IBinder windowToken) {
+        mHandler.post(() -> {
+            if (mCallback != callback || mWindowToken != windowToken) {
+                hideAllUiThread();
+                mCallback = callback;
+                mWindowToken = windowToken;
+            }
+        });
+    }
+
+    /**
+     * Displays an error message to the user.
+     */
+    public void showError(@Nullable CharSequence message) {
+        mHandler.post(() -> {
+            if (!hasCallback()) {
+                return;
+            }
+            hideAllUiThread();
+            if (!TextUtils.isEmpty(message)) {
+                Toast.makeText(mContext, message, Toast.LENGTH_LONG).show();
+            }
+        });
+    }
+
+    /**
+     * Hides the fill UI.
+     */
+    public void hideFillUi() {
+        mHandler.post(this::hideFillUiUiThread);
+    }
+
+    /**
+     * Filters the options in the fill UI.
+     *
+     * @param filterText The filter prefix.
+     */
+    public void filterFillUi(@Nullable String filterText) {
+        mHandler.post(() -> {
+            if (!hasCallback()) {
+                return;
+            }
+            hideSaveUiUiThread();
+            if (mFillUi != null) {
+                mFillUi.filter(filterText);
+            }
+        });
+    }
+
+    /**
+     * Updates the position of the fill UI.
+     *
+     * @param anchoredBounds The bounds of the anchor view.
+     */
+    public void updateFillUi(@NonNull Rect anchoredBounds) {
+        mHandler.post(() -> {
+            if (!hasCallback()) {
+                return;
+            }
+            hideSaveUiUiThread();
+            if (mFillUi != null) {
+                mFillUi.update(anchoredBounds);
+            }
+        });
+    }
+
+    /**
+     * Shows the fill UI, removing the previous fill UI if the has changed.
+     *
+     * @param focusedId the currently focused field
+     * @param response the current fill response
+     * @param anchorBounds bounds of the focused view
+     * @param filterText text of the view to be filled
+     */
+    public void showFillUi(@NonNull AutoFillId focusedId, @NonNull FillResponse response,
+            @NonNull Rect anchorBounds, @Nullable String filterText) {
+        mHandler.post(() -> {
+            if (!hasCallback()) {
+                return;
+            }
+            hideAllUiThread();
+            mFillUi = new FillUi(mContext, response, focusedId,
+                    mWindowToken, anchorBounds, filterText, new FillUi.Callback() {
+                @Override
+                public void onResponsePicked(FillResponse response) {
+                    hideFillUiUiThread();
+                    if (mCallback != null) {
+                        mCallback.authenticate(response.getAuthentication());
+                    }
+                }
+
+                @Override
+                public void onDatasetPicked(Dataset dataset) {
+                    hideFillUiUiThread();
+                    if (mCallback != null) {
+                        mCallback.fill(dataset);
+                    }
+                    // TODO(b/33197203): add MetricsLogger call
+                }
+
+                @Override
+                public void onCanceled() {
+                    hideFillUiUiThread();
+                    // TODO(b/33197203): add MetricsLogger call
+                }
+            });
+        });
+    }
+
+    /**
+     * Shows the UI asking the user to save for auto-fill.
+     */
+    public void showSaveUi(@NonNull CharSequence providerLabel) {
+        mHandler.post(() -> {
+            if (!hasCallback()) {
+                return;
+            }
+            hideAllUiThread();
+            mSaveUi = new SaveUi(mContext, providerLabel,
+                    new SaveUi.OnSaveListener() {
+                @Override
+                public void onSave() {
+                    hideSaveUiUiThread();
+                    if (mCallback != null) {
+                        mCallback.save();
+                    }
+                    // TODO(b/33197203): add MetricsLogger call
+                }
+
+                @Override
+                public void onCancel() {
+                    // TODO(b/33197203): add MetricsLogger call
+                    hideSaveUiUiThread();
+                }
+            });
+        });
+    }
+
+    /**
+     * Hides all UI affordances.
+     */
+    public void hideAll() {
+        mHandler.post(this::hideAllUiThread);
+    }
+
+    public void dump(PrintWriter pw) {
+        pw.println("AufoFill UI");
+        final String prefix = "  ";
+        pw.print(prefix); pw.print("showsFillUi: "); pw.println(mFillUi != null);
+        pw.print(prefix); pw.print("showsSaveUi: "); pw.println(mSaveUi != null);
+    }
+
+    @android.annotation.UiThread
+    private void hideFillUiUiThread() {
+        if (mFillUi != null) {
+            mFillUi.destroy();
+            mFillUi = null;
+        }
+    }
+
+    @android.annotation.UiThread
+    private void hideSaveUiUiThread() {
+        if (mSaveUi != null) {
+            mSaveUi.destroy();
+            mSaveUi = null;
+        }
+    }
+
+    @android.annotation.UiThread
+    private void hideAllUiThread() {
+        hideFillUiUiThread();
+        hideSaveUiUiThread();
+    }
+
+    private boolean hasCallback() {
+        return mCallback != null;
+    }
+}
diff --git a/services/autofill/java/com/android/server/autofill/ui/FillUi.java b/services/autofill/java/com/android/server/autofill/ui/FillUi.java
new file mode 100644
index 0000000..0d5fbbe
--- /dev/null
+++ b/services/autofill/java/com/android/server/autofill/ui/FillUi.java
@@ -0,0 +1,348 @@
+/*
+ * 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.server.autofill.ui;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.Context;
+import android.graphics.PixelFormat;
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.os.IBinder;
+import android.service.autofill.Dataset;
+import android.service.autofill.FillResponse;
+import android.util.Slog;
+import android.view.Gravity;
+import android.view.LayoutInflater;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.View.MeasureSpec;
+import android.view.ViewGroup;
+import android.view.WindowManager;
+import android.view.autofill.AutoFillId;
+import android.view.autofill.AutoFillValue;
+import android.widget.ArrayAdapter;
+import android.widget.ListView;
+import com.android.internal.R;
+import com.android.internal.R;
+import libcore.util.Objects;
+
+import java.util.ArrayList;
+
+final class FillUi {
+    private static final String TAG = "FillUi";
+
+    interface Callback {
+        void onResponsePicked(@NonNull FillResponse response);
+        void onDatasetPicked(@NonNull Dataset dataset);
+        void onCanceled();
+    }
+
+    private final Rect mAnchorBounds = new Rect();
+
+    private final @NonNull AnchoredWindow mWindow;
+
+    private final @NonNull Callback mCallback;
+
+    private final @Nullable ArrayAdapter<ViewItem> mAdapter;
+
+    private @Nullable String mFilterText;
+
+    private int mContentWidth;
+    private int mContentHeight;
+
+    private boolean mDestroyed;
+
+    FillUi(@NonNull Context context, @NonNull FillResponse response,
+            @NonNull AutoFillId focusedViewId, @NonNull IBinder windowToken,
+            @NonNull Rect anchorBounds, @Nullable String filterText,
+            @NonNull Callback callback) {
+        mAnchorBounds.set(anchorBounds);
+        mCallback = callback;
+
+        if (response.getAuthentication() != null) {
+            final View content;
+            try {
+                content = response.getPresentation().apply(context, null);
+            } catch (RuntimeException e) {
+                callback.onCanceled();
+                Slog.e(TAG, "Error inflating remote views", e);
+                mWindow = null;
+                mAdapter = null;
+                return;
+            }
+            final int widthMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, 0);
+            final int heightMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, 0);
+            content.measure(widthMeasureSpec, heightMeasureSpec);
+            content.setOnClickListener(v -> mCallback.onResponsePicked(response));
+            mContentWidth = content.getMeasuredWidth();
+            mContentHeight = content.getMeasuredHeight();
+            mAdapter = null;
+
+            mWindow = new AnchoredWindow(windowToken, content);
+            mWindow.update(mContentWidth, mContentHeight, mAnchorBounds);
+        } else {
+            final int datasetCount = response.getDatasets().size();
+            final ArrayList<ViewItem> items = new ArrayList<>(datasetCount);
+            for (int i = 0; i < datasetCount; i++) {
+                final Dataset dataset = response.getDatasets().get(i);
+                final int index = dataset.getFieldIds().indexOf(focusedViewId);
+                if (index >= 0) {
+                    AutoFillValue value = dataset.getFieldValues().get(index);
+                    final View view;
+                    try {
+                        view = dataset.getPresentation().apply(context, null);
+                    } catch (RuntimeException e) {
+                        Slog.e(TAG, "Error inflating remote views", e);
+                        continue;
+                    }
+                    items.add(new ViewItem(dataset, value.coerceToString()
+                            .toLowerCase(), view));
+                }
+            }
+
+            mAdapter = new ArrayAdapter<ViewItem>(context, 0, items) {
+                @Override
+                public View getView(int position, View convertView, ViewGroup parent) {
+                    return getItem(position).getView();
+                }
+            };
+
+            final LayoutInflater inflater = LayoutInflater.from(context);
+            final ListView listView = (ListView) inflater.inflate(
+                    com.android.internal.R.layout.autofill_dataset_picker, null);
+            listView.setAdapter(mAdapter);
+            listView.setOnItemClickListener((adapter, view, position, id) -> {
+                final ViewItem vi = mAdapter.getItem(position);
+                mCallback.onDatasetPicked(vi.getDataset());
+            });
+
+            filter(filterText);
+            mWindow = new AnchoredWindow(windowToken, listView);
+        }
+    }
+
+    public void update(@NonNull Rect anchorBounds) {
+        throwIfDestroyed();
+        if (!mAnchorBounds.equals(anchorBounds)) {
+            mAnchorBounds.set(anchorBounds);
+            mWindow.update(mContentWidth, mContentHeight, anchorBounds);
+        }
+    }
+
+    public void filter(@Nullable String filterText) {
+        throwIfDestroyed();
+        if (mAdapter == null) {
+            return;
+        }
+        if (Objects.equal(mFilterText, filterText)) {
+            return;
+        }
+        mFilterText = filterText;
+        mAdapter.getFilter().filter(filterText, (count) -> {
+            if (mDestroyed) {
+                return;
+            }
+            if (count <= 0) {
+                mCallback.onCanceled();
+            } else {
+                if (updateContentSize()) {
+                    mWindow.update(mContentWidth, mContentHeight, mAnchorBounds);
+                }
+            }
+        });
+    }
+
+    public void destroy() {
+        throwIfDestroyed();
+        mWindow.destroy();
+        mDestroyed = true;
+    }
+
+    private boolean updateContentSize() {
+        if (mAdapter == null) {
+            return false;
+        }
+        boolean changed = false;
+        if (mAdapter.getCount() <= 0) {
+            if (mContentWidth != 0) {
+                mContentWidth = 0;
+                changed = true;
+            }
+            if (mContentHeight != 0) {
+                mContentHeight = 0;
+                changed = true;
+            }
+            return changed;
+        }
+
+        mContentWidth = 0;
+        mContentHeight = 0;
+
+        final int widthMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, 0);
+        final int heightMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, 0);
+        final int itemCount = mAdapter.getCount();
+        for (int i = 0; i < itemCount; i++) {
+            View view = mAdapter.getItem(i).getView();
+            view.measure(widthMeasureSpec, heightMeasureSpec);
+            final int newContentWidth = Math.max(mContentWidth, view.getMeasuredWidth());
+            if (newContentWidth != mContentWidth) {
+                mContentWidth = newContentWidth;
+                changed = true;
+            }
+            final int newContentHeight = mContentHeight + view.getMeasuredHeight();
+            if (newContentHeight != mContentHeight) {
+                mContentHeight = newContentHeight;
+                changed = true;
+            }
+        }
+        return changed;
+    }
+
+    private void throwIfDestroyed() {
+        if (mDestroyed) {
+            throw new IllegalStateException("cannot interact with a destroyed instance");
+        }
+    }
+
+    private static class ViewItem {
+        private final String mValue;
+        private final Dataset mDataset;
+        private final View mView;
+
+        ViewItem(Dataset dataset, String value, View view) {
+            mDataset = dataset;
+            mValue = value.toLowerCase();
+            mView = view;
+        }
+
+        public View getView() {
+            return mView;
+        }
+
+        public Dataset getDataset() {
+            return mDataset;
+        }
+
+        @Override
+        public String toString() {
+            // Used for filtering in the adapter
+            return mValue;
+        }
+    }
+
+    final class AnchoredWindow implements View.OnTouchListener {
+        private final Point mTempPoint = new Point();
+
+        private final WindowManager mWm;
+
+        private final IBinder mActivityToken;
+        private final View mContentView;
+
+        /**
+         * Constructor.
+         *
+         * @param activityToken token to pass to window manager
+         * @param contentView content of the window
+         */
+        AnchoredWindow(IBinder activityToken, View contentView) {
+            mWm = contentView.getContext().getSystemService(WindowManager.class);
+            mActivityToken = activityToken;
+            mContentView = contentView;
+        }
+
+        /**
+         * Hides the window.
+         */
+        void destroy() {
+            if (mContentView.isAttachedToWindow()) {
+                mContentView.setOnTouchListener(null);
+                mWm.removeView(mContentView);
+            }
+        }
+
+        @Override
+        public boolean onTouch(View view, MotionEvent event) {
+            // When the window is touched outside, hide the window.
+            if (view == mContentView && event.getAction() == MotionEvent.ACTION_OUTSIDE) {
+                mCallback.onCanceled();
+                return true;
+            }
+            return false;
+        }
+
+        public void update(int desiredWidth, int desiredHeight, Rect anchorBounds) {
+            final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
+            params.setTitle("FillUi");
+            params.token = mActivityToken;
+            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
+            params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
+                    | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
+                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
+                    | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
+                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
+            params.format = PixelFormat.TRANSLUCENT;
+
+            mWm.getDefaultDisplay().getRealSize(mTempPoint);
+            final int screenWidth = mTempPoint.x;
+            final int screenHeight = mTempPoint.y;
+
+            // Try to place the window at the start of the anchor view if
+            // there is space to fit the content, otherwise fit as much of
+            // the window as possible moving it to the left using all available
+            // screen width.
+            params.x = Math.min(anchorBounds.left, Math.max(screenWidth - desiredWidth, 0));
+            params.width = Math.min(screenWidth, desiredWidth);
+
+            // Try to fit below using all available space with top-start gravity
+            // and if that fails try to fit above using all available space with
+            // bottom-start gravity.
+            final int verticalSpaceBelow = screenHeight - anchorBounds.bottom;
+            if (desiredHeight <= verticalSpaceBelow) {
+                // Fits below bounds.
+                params.height = desiredHeight;
+                params.gravity = Gravity.TOP | Gravity.START;
+                params.y = anchorBounds.bottom;
+            } else {
+                final int verticalSpaceAbove = anchorBounds.top;
+                if (desiredHeight <= verticalSpaceAbove) {
+                    // Fits above bounds.
+                    params.height = desiredHeight;
+                    params.gravity = Gravity.BOTTOM | Gravity.START;
+                    params.y = anchorBounds.top + desiredHeight;
+                } else {
+                    // Pick above/below based on which has the most space.
+                    if (verticalSpaceBelow >= verticalSpaceAbove) {
+                        params.height = verticalSpaceBelow;
+                        params.gravity = Gravity.TOP | Gravity.START;
+                        params.y = anchorBounds.bottom;
+                    } else {
+                        params.height = verticalSpaceAbove;
+                        params.gravity = Gravity.BOTTOM | Gravity.START;
+                        params.y = anchorBounds.top + desiredHeight;
+                    }
+                }
+            }
+
+            if (!mContentView.isAttachedToWindow()) {
+                mWm.addView(mContentView, params);
+                mContentView.setOnTouchListener(this);
+            } else {
+                mWm.updateViewLayout(mContentView, params);
+            }
+        }
+    }
+}
diff --git a/services/autofill/java/com/android/server/autofill/ui/SaveUi.java b/services/autofill/java/com/android/server/autofill/ui/SaveUi.java
new file mode 100644
index 0000000..b7215d6
--- /dev/null
+++ b/services/autofill/java/com/android/server/autofill/ui/SaveUi.java
@@ -0,0 +1,103 @@
+/*
+ * 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.server.autofill.ui;
+
+import android.annotation.NonNull;
+import android.app.Dialog;
+import android.content.Context;
+import android.os.Handler;
+import android.text.format.DateUtils;
+import android.view.Gravity;
+import android.view.Window;
+import android.view.WindowManager;
+import android.widget.TextView;
+import android.view.LayoutInflater;
+import android.view.View;
+
+import com.android.internal.R;
+import com.android.server.UiThread;
+
+/**
+ * Autofill Save Prompt
+ */
+final class SaveUi {
+    public interface OnSaveListener {
+        void onSave();
+        void onCancel();
+    }
+
+    private static final long LIFETIME_MILLIS = 5 * DateUtils.SECOND_IN_MILLIS;
+
+    private final Handler mHandler = UiThread.getHandler();
+
+    private final @NonNull Dialog mDialog;
+
+    private final @NonNull OnSaveListener mListener;
+
+    private boolean mDestroyed;
+
+    SaveUi(@NonNull Context context, @NonNull CharSequence providerLabel,
+            @NonNull OnSaveListener listener) {
+        mListener = listener;
+
+        final LayoutInflater inflater = LayoutInflater.from(context);
+        final View view = inflater.inflate(R.layout.autofill_save, null);
+
+        final TextView title = (TextView) view.findViewById(R.id.autofill_save_title);
+        title.setText(context.getString(R.string.autofill_save_title, providerLabel));
+
+        final View noButton = view.findViewById(R.id.autofill_save_no);
+        noButton.setOnClickListener((v) -> mListener.onCancel());
+
+        final View yesButton = view.findViewById(R.id.autofill_save_yes);
+        yesButton.setOnClickListener((v) -> mListener.onSave());
+
+        final View closeButton = view.findViewById(R.id.autofill_save_close);
+        closeButton.setOnClickListener((v) -> mListener.onCancel());
+
+        mDialog = new Dialog(context, R.style.Theme_Material_Panel);
+        mDialog.setContentView(view);
+
+        final Window window = mDialog.getWindow();
+        window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
+        window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
+                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
+                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
+                | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
+        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
+        window.setGravity(Gravity.BOTTOM | Gravity.CENTER);
+        window.setCloseOnTouchOutside(true);
+        window.getAttributes().width = WindowManager.LayoutParams.MATCH_PARENT;
+
+        mDialog.show();
+
+        mHandler.postDelayed(() -> mListener.onCancel(), LIFETIME_MILLIS);
+    }
+
+    void destroy() {
+        throwIfDestroyed();
+        mHandler.removeCallbacksAndMessages(mListener);
+        mDialog.dismiss();
+        mDestroyed = true;
+    }
+
+    private void throwIfDestroyed() {
+        if (mDestroyed) {
+            throw new IllegalStateException("cannot interact with a destroyed instance");
+        }
+    }
+}
diff --git a/services/backup/java/com/android/server/backup/BackupManagerService.java b/services/backup/java/com/android/server/backup/BackupManagerService.java
index b459f74..4f8b8af 100644
--- a/services/backup/java/com/android/server/backup/BackupManagerService.java
+++ b/services/backup/java/com/android/server/backup/BackupManagerService.java
@@ -38,15 +38,15 @@
 import android.app.backup.BackupTransport;
 import android.app.backup.FullBackup;
 import android.app.backup.FullBackupDataOutput;
-import android.app.backup.IBackupObserver;
-import android.app.backup.IBackupManagerMonitor;
-import android.app.backup.RestoreDescription;
-import android.app.backup.RestoreSet;
 import android.app.backup.IBackupManager;
+import android.app.backup.IBackupManagerMonitor;
+import android.app.backup.IBackupObserver;
 import android.app.backup.IFullBackupRestoreObserver;
 import android.app.backup.IRestoreObserver;
 import android.app.backup.IRestoreSession;
 import android.app.backup.ISelectBackupTransportCallback;
+import android.app.backup.RestoreDescription;
+import android.app.backup.RestoreSet;
 import android.app.backup.SelectBackupTransportCallback;
 import android.content.ActivityNotFoundException;
 import android.content.BroadcastReceiver;
@@ -136,6 +136,7 @@
 import java.security.spec.InvalidKeySpecException;
 import java.security.spec.KeySpec;
 import java.text.SimpleDateFormat;
+import java.util.ArrayDeque;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -146,6 +147,7 @@
 import java.util.List;
 import java.util.Map.Entry;
 import java.util.Objects;
+import java.util.Queue;
 import java.util.Random;
 import java.util.Set;
 import java.util.TreeMap;
@@ -327,6 +329,11 @@
     final Object mClearDataLock = new Object();
     volatile boolean mClearingData;
 
+    @GuardedBy("mPendingRestores")
+    private boolean mIsRestoreInProgress;
+    @GuardedBy("mPendingRestores")
+    private final Queue<PerformUnifiedRestoreTask> mPendingRestores = new ArrayDeque<>();
+
     ActiveRestoreSession mActiveRestoreSession;
 
     // Watch the device provisioning operation during setup
@@ -909,11 +916,28 @@
             {
                 RestoreParams params = (RestoreParams)msg.obj;
                 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
-                BackupRestoreTask task = new PerformUnifiedRestoreTask(params.transport,
+
+                PerformUnifiedRestoreTask task = new PerformUnifiedRestoreTask(params.transport,
                         params.observer, params.monitor, params.token, params.pkgInfo,
                         params.pmToken, params.isSystemRestore, params.filterSet);
-                Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
-                sendMessage(restoreMsg);
+
+                synchronized (mPendingRestores) {
+                    if (mIsRestoreInProgress) {
+                        if (DEBUG) {
+                            Slog.d(TAG, "Restore in progress, queueing.");
+                        }
+                        mPendingRestores.add(task);
+                        // This task will be picked up and executed when the the currently running
+                        // restore task finishes.
+                    } else {
+                        if (DEBUG) {
+                            Slog.d(TAG, "Starting restore.");
+                        }
+                        mIsRestoreInProgress = true;
+                        Message restoreMsg = obtainMessage(MSG_BACKUP_RESTORE_STEP, task);
+                        sendMessage(restoreMsg);
+                    }
+                }
                 break;
             }
 
@@ -2658,19 +2682,32 @@
             mStateDir = new File(mBaseStateDir, dirName);
             mCurrentOpToken = generateToken();
 
-            mCurrentState = BackupState.INITIAL;
             mFinished = false;
 
-            CountDownLatch latch = new CountDownLatch(1);
-            String[] fullBackups =
-                    mPendingFullBackups.toArray(new String[mPendingFullBackups.size()]);
-            mFullBackupTask =
-                    new PerformFullTransportBackupTask(/*fullBackupRestoreObserver*/ null,
-                            fullBackups, /*updateSchedule*/ false, /*runningJob*/ null, latch,
-                            mObserver, mMonitor,mUserInitiated);
+            synchronized (mCurrentOpLock) {
+                if (isBackupOperationInProgress()) {
+                    if (DEBUG) {
+                        Slog.d(TAG, "Skipping backup since one is already in progress.");
+                    }
+                    mCancelAll = true;
+                    mFullBackupTask = null;
+                    mCurrentState = BackupState.FINAL;
+                    addBackupTrace("Skipped. Backup already in progress.");
+                } else {
+                    mCurrentState = BackupState.INITIAL;
+                    CountDownLatch latch = new CountDownLatch(1);
+                    String[] fullBackups =
+                            mPendingFullBackups.toArray(new String[mPendingFullBackups.size()]);
+                    mFullBackupTask =
+                            new PerformFullTransportBackupTask(/*fullBackupRestoreObserver*/ null,
+                                    fullBackups, /*updateSchedule*/ false, /*runningJob*/ null,
+                                    latch,
+                                    mObserver, mMonitor, mUserInitiated);
 
-            registerTask();
-            addBackupTrace("STATE => INITIAL");
+                    registerTask();
+                    addBackupTrace("STATE => INITIAL");
+                }
+            }
         }
 
         /**
@@ -3053,7 +3090,9 @@
                 mWakelock.acquire();
                 (new Thread(mFullBackupTask, "full-transport-requested")).start();
             } else if (mCancelAll) {
-                mFullBackupTask.unregisterTask();
+                if (mFullBackupTask != null) {
+                    mFullBackupTask.unregisterTask();
+                }
                 sendBackupFinished(mObserver, BackupManager.ERROR_BACKUP_CANCELLED);
             } else {
                 mFullBackupTask.unregisterTask();
@@ -3537,6 +3576,18 @@
         }
     }
 
+    private boolean isBackupOperationInProgress() {
+        synchronized (mCurrentOpLock) {
+            for (int i = 0; i < mCurrentOperations.size(); i++) {
+                Operation op = mCurrentOperations.valueAt(i);
+                if (op.type == OP_TYPE_BACKUP && op.state == OP_PENDING) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
 
     // ----- Full backup/restore to a file/socket -----
 
@@ -4519,6 +4570,14 @@
             mCurrentOpToken = generateToken();
             mBackupRunnerOpToken = generateToken();
 
+            if (isBackupOperationInProgress()) {
+                if (DEBUG) {
+                    Slog.d(TAG, "Skipping full backup. A backup is already in progress.");
+                }
+                mCancelAll = true;
+                return;
+            }
+
             registerTask();
 
             for (String pkg : whichPackages) {
@@ -9148,6 +9207,24 @@
 
             // done; we can finally release the wakelock and be legitimately done.
             Slog.i(TAG, "Restore complete.");
+
+            synchronized (mPendingRestores) {
+                if (mPendingRestores.size() > 0) {
+                    if (DEBUG) {
+                        Slog.d(TAG, "Starting next pending restore.");
+                    }
+                    PerformUnifiedRestoreTask task = mPendingRestores.remove();
+                    mBackupHandler.sendMessage(
+                            mBackupHandler.obtainMessage(MSG_BACKUP_RESTORE_STEP, task));
+
+                } else {
+                    mIsRestoreInProgress = false;
+                    if (MORE_DEBUG) {
+                        Slog.d(TAG, "No pending restores.");
+                    }
+                }
+            }
+
             mWakelock.release();
         }
 
diff --git a/services/core/java/com/android/server/GraphicsStatsService.java b/services/core/java/com/android/server/GraphicsStatsService.java
index bdd80e38..14a9a31 100644
--- a/services/core/java/com/android/server/GraphicsStatsService.java
+++ b/services/core/java/com/android/server/GraphicsStatsService.java
@@ -137,16 +137,21 @@
     }
 
     private void onAlarm() {
+        // We need to make a copy since some of the callbacks won't be proxy and thus
+        // can result in a re-entrant acquisition of mLock that would result in a modification
+        // of mActive during iteration.
+        ActiveBuffer[] activeCopy;
         synchronized (mLock) {
             mRotateIsScheduled = false;
             scheduleRotateLocked();
-            for (ActiveBuffer active : mActive) {
-                try {
-                    active.mCallback.onRotateGraphicsStatsBuffer();
-                } catch (RemoteException e) {
-                    Log.w(TAG, String.format("Failed to notify '%s' (pid=%d) to rotate buffers",
-                            active.mInfo.packageName, active.mPid), e);
-                }
+            activeCopy = mActive.toArray(new ActiveBuffer[0]);
+        }
+        for (ActiveBuffer active : activeCopy) {
+            try {
+                active.mCallback.onRotateGraphicsStatsBuffer();
+            } catch (RemoteException e) {
+                Log.w(TAG, String.format("Failed to notify '%s' (pid=%d) to rotate buffers",
+                        active.mInfo.packageName, active.mPid), e);
             }
         }
         // Give a few seconds for everyone to rotate before doing the cleanup
diff --git a/services/core/java/com/android/server/InputMethodManagerService.java b/services/core/java/com/android/server/InputMethodManagerService.java
index fe5b3a2..b95ed08 100644
--- a/services/core/java/com/android/server/InputMethodManagerService.java
+++ b/services/core/java/com/android/server/InputMethodManagerService.java
@@ -881,7 +881,7 @@
 
     final class MyPackageMonitor extends PackageMonitor {
         /**
-         * Set of packages to be monitored.
+         * Package names that are known to contain {@link InputMethodService}.
          *
          * <p>No need to include packages because of direct-boot unaware IMEs since we always rescan
          * all the packages when the user is unlocked, and direct-boot awareness will not be changed
@@ -889,16 +889,36 @@
          * rescanning.</p>
          */
         @GuardedBy("mMethodMap")
-        private ArraySet<String> mPackagesToMonitorComponentChange = new ArraySet<>();
+        final private ArraySet<String> mKnownImePackageNames = new ArraySet<>();
+
+        /**
+         * Packages that are appeared, disappeared, or modified for whatever reason.
+         *
+         * <p>Note: For now we intentionally use {@link ArrayList} instead of {@link ArraySet}
+         * because 1) the number of elements is almost always 1 or so, and 2) we do not care
+         * duplicate elements for our use case.</p>
+         *
+         * <p>This object must be accessed only from callback methods in {@link PackageMonitor},
+         * which should be bound to {@link #getRegisteredHandler()}.</p>
+         */
+        private final ArrayList<String> mChangedPackages = new ArrayList<>();
+
+        /**
+         * {@code true} if one or more packages that contain {@link InputMethodService} appeared.
+         *
+         * <p>This field must be accessed only from callback methods in {@link PackageMonitor},
+         * which should be bound to {@link #getRegisteredHandler()}.</p>
+         */
+        private boolean mImePackageAppeared = false;
 
         @GuardedBy("mMethodMap")
-        void clearPackagesToMonitorComponentChangeLocked() {
-            mPackagesToMonitorComponentChange.clear();
+        void clearKnownImePackageNamesLocked() {
+            mKnownImePackageNames.clear();
         }
 
         @GuardedBy("mMethodMap")
-        final void addPackageToMonitorComponentChangeLocked(@NonNull String packageName) {
-            mPackagesToMonitorComponentChange.add(packageName);
+        final void addKnownImePackageNameLocked(@NonNull String packageName) {
+            mKnownImePackageNames.add(packageName);
         }
 
         @GuardedBy("mMethodMap")
@@ -943,19 +963,97 @@
         }
 
         @Override
-        public boolean onPackageChanged(String packageName, int uid, String[] components) {
-            // If this package is in the watch list, we want to check it.
-            synchronized (mMethodMap) {
-                return mPackagesToMonitorComponentChange.contains(packageName);
+        public void onBeginPackageChanges() {
+            clearPackageChangeState();
+        }
+
+        @Override
+        public void onPackageAppeared(String packageName, int reason) {
+            if (!mImePackageAppeared) {
+                final PackageManager pm = mContext.getPackageManager();
+                final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
+                        new Intent(InputMethod.SERVICE_INTERFACE).setPackage(packageName),
+                        PackageManager.MATCH_DISABLED_COMPONENTS, getChangingUserId());
+                // No need to lock this because we access it only on getRegisteredHandler().
+                if (!services.isEmpty()) {
+                    mImePackageAppeared = true;
+                }
+            }
+            // No need to lock this because we access it only on getRegisteredHandler().
+            mChangedPackages.add(packageName);
+        }
+
+        @Override
+        public void onPackageDisappeared(String packageName, int reason) {
+            // No need to lock this because we access it only on getRegisteredHandler().
+            mChangedPackages.add(packageName);
+        }
+
+        @Override
+        public void onPackageModified(String packageName) {
+            // No need to lock this because we access it only on getRegisteredHandler().
+            mChangedPackages.add(packageName);
+        }
+
+        @Override
+        public void onPackagesSuspended(String[] packages) {
+            // No need to lock this because we access it only on getRegisteredHandler().
+            for (String packageName : packages) {
+                mChangedPackages.add(packageName);
             }
         }
 
         @Override
-        public void onSomePackagesChanged() {
+        public void onPackagesUnsuspended(String[] packages) {
+            // No need to lock this because we access it only on getRegisteredHandler().
+            for (String packageName : packages) {
+                mChangedPackages.add(packageName);
+            }
+        }
+
+        @Override
+        public void onFinishPackageChanges() {
+            onFinishPackageChangesInternal();
+            clearPackageChangeState();
+        }
+
+        private void clearPackageChangeState() {
+            // No need to lock them because we access these fields only on getRegisteredHandler().
+            mChangedPackages.clear();
+            mImePackageAppeared = false;
+        }
+
+        private boolean shouldRebuildInputMethodListLocked() {
+            // This method is guaranteed to be called only by getRegisteredHandler().
+
+            // If there is any new package that contains at least one IME, then rebuilt the list
+            // of IMEs.
+            if (mImePackageAppeared) {
+                return true;
+            }
+
+            // Otherwise, check if mKnownImePackageNames and mChangedPackages have any intersection.
+            // TODO: Consider to create a utility method to do the following test. List.retainAll()
+            // is an option, but it may still do some extra operations that we do not need here.
+            final int N = mChangedPackages.size();
+            for (int i = 0; i < N; ++i) {
+                final String packageName = mChangedPackages.get(i);
+                if (mKnownImePackageNames.contains(packageName)) {
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        private void onFinishPackageChangesInternal() {
             synchronized (mMethodMap) {
                 if (!isChangingPackagesOfCurrentUserLocked()) {
                     return;
                 }
+                if (!shouldRebuildInputMethodListLocked()) {
+                    return;
+                }
+
                 InputMethodInfo curIm = null;
                 String curInputMethodId = mSettings.getSelectedInputMethod();
                 final int N = mMethodList.size();
@@ -3283,7 +3381,7 @@
         mMethodList.clear();
         mMethodMap.clear();
         mMethodMapUpdateCount++;
-        mMyPackageMonitor.clearPackagesToMonitorComponentChangeLocked();
+        mMyPackageMonitor.clearKnownImePackageNamesLocked();
 
         // Use for queryIntentServicesAsUser
         final PackageManager pm = mContext.getPackageManager();
@@ -3339,10 +3437,9 @@
             final int N = allInputMethodServices.size();
             for (int i = 0; i < N; ++i) {
                 final ServiceInfo si = allInputMethodServices.get(i).serviceInfo;
-                if (!android.Manifest.permission.BIND_INPUT_METHOD.equals(si.permission)) {
-                    continue;
+                if (android.Manifest.permission.BIND_INPUT_METHOD.equals(si.permission)) {
+                    mMyPackageMonitor.addKnownImePackageNameLocked(si.packageName);
                 }
-                mMyPackageMonitor.addPackageToMonitorComponentChangeLocked(si.packageName);
             }
         }
 
diff --git a/services/core/java/com/android/server/RescueParty.java b/services/core/java/com/android/server/RescueParty.java
index 33351ff..480b08a 100644
--- a/services/core/java/com/android/server/RescueParty.java
+++ b/services/core/java/com/android/server/RescueParty.java
@@ -19,13 +19,9 @@
 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.pm.UserInfo;
-import android.os.BatteryManager;
-import android.os.BatteryProperties;
 import android.os.Build;
-import android.os.IBatteryPropertiesListener;
-import android.os.IBatteryPropertiesRegistrar;
+import android.os.FileUtils;
 import android.os.RecoverySystem;
-import android.os.ServiceManager;
 import android.os.SystemClock;
 import android.os.SystemProperties;
 import android.os.UserHandle;
@@ -34,14 +30,12 @@
 import android.text.format.DateUtils;
 import android.util.ExceptionUtils;
 import android.util.MathUtils;
-import android.util.MutableBoolean;
 import android.util.Slog;
 import android.util.SparseArray;
 
 import com.android.internal.util.ArrayUtils;
 
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
+import java.io.File;
 
 /**
  * Utilities to help rescue the system from crash loops. Callers are expected to
@@ -325,30 +319,13 @@
 
     /**
      * Hacky test to check if the device has an active USB connection, which is
-     * a good proxy for someone doing local development work. It uses a low
-     * level call since we may not have started {@link BatteryManager} yet.
+     * a good proxy for someone doing local development work.
      */
     private static boolean isUsbActive() {
-        final MutableBoolean res = new MutableBoolean(false);
-        final CountDownLatch latch = new CountDownLatch(1);
-        final IBatteryPropertiesListener listener = new IBatteryPropertiesListener.Stub() {
-            @Override
-            public void batteryPropertiesChanged(BatteryProperties props) {
-                res.value = props.chargerUsbOnline;
-                latch.countDown();
-            }
-        };
-
         try {
-            final IBatteryPropertiesRegistrar bpr = IBatteryPropertiesRegistrar.Stub
-                    .asInterface(ServiceManager.getService("batteryproperties"));
-            bpr.registerListener(listener);
-            try {
-                latch.await(5, TimeUnit.SECONDS);
-            } finally {
-                bpr.unregisterListener(listener);
-            }
-            return res.value;
+            final String state = FileUtils
+                    .readTextFile(new File("/sys/class/android_usb/android0/state"), 128, "");
+            return "CONFIGURED".equals(state.trim());
         } catch (Throwable t) {
             Slog.w(TAG, "Failed to determine if device was on USB", t);
             return false;
diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java
index cec5800..2bc131f 100644
--- a/services/core/java/com/android/server/am/ActiveServices.java
+++ b/services/core/java/com/android/server/am/ActiveServices.java
@@ -703,27 +703,21 @@
         return false;
     }
 
-    public long setServiceForegroundLocked(ComponentName className, IBinder token,
+    public void setServiceForegroundLocked(ComponentName className, IBinder token,
             int id, Notification notification, int flags) {
         final int userId = UserHandle.getCallingUserId();
         final long origId = Binder.clearCallingIdentity();
         try {
             ServiceRecord r = findServiceLocked(className, token, userId);
             if (r != null) {
-                return setServiceForegroundInnerLocked(r, id, notification, flags);
+                setServiceForegroundInnerLocked(r, id, notification, flags);
             }
-            return ActivityThread.INVALID_PROC_STATE_SEQ;
         } finally {
             Binder.restoreCallingIdentity(origId);
         }
     }
 
-    /**
-     * @return current process state sequence number {@link UidRecord#curProcStateSeq} corresponding
-     *         to the ServiceRecord {@param r} if the calling service has to block until the
-     *         network rules are udpated, Otherwise {@link ActivityThread#INVALID_PROC_STATE_SEQ}.
-     */
-    private long setServiceForegroundInnerLocked(ServiceRecord r, int id,
+    private void setServiceForegroundInnerLocked(ServiceRecord r, int id,
             Notification notification, int flags) {
         if (id != 0) {
             if (notification == null) {
@@ -742,7 +736,7 @@
                         Slog.w(TAG, "Instant app " + r.appInfo.packageName
                                 + " does not have permission to create foreground services"
                                 + ", ignoring.");
-                        return ActivityThread.INVALID_PROC_STATE_SEQ;
+                        return;
                     case AppOpsManager.MODE_ERRORED:
                         throw new SecurityException("Instant app " + r.appInfo.packageName
                                 + " does not have permission to create foreground services");
@@ -770,18 +764,12 @@
             r.foregroundNoti = notification;
             r.isForeground = true;
             r.postNotification();
-            long procStateSeqToReturn = ActivityThread.INVALID_PROC_STATE_SEQ;
             if (r.app != null) {
                 updateServiceForegroundLocked(r.app, true);
-                if (r.app.uidRecord != null &&
-                        r.app.uidRecord.blockState == ActivityThread.NETWORK_STATE_BLOCK) {
-                    procStateSeqToReturn = r.app.uidRecord.curProcStateSeq;
-                }
             }
             getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
             mAm.notifyPackageUse(r.serviceInfo.packageName,
                                  PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
-            return procStateSeqToReturn;
         } else {
             if (r.isForeground) {
                 r.isForeground = false;
@@ -802,7 +790,6 @@
                 }
             }
         }
-        return ActivityThread.INVALID_PROC_STATE_SEQ;
     }
 
     private void cancelForegroudNotificationLocked(ServiceRecord r) {
diff --git a/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java b/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java
index 8ed95ee..88e0d03 100644
--- a/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java
+++ b/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java
@@ -63,7 +63,6 @@
     static final boolean DEBUG_LOCKTASK = DEBUG_ALL || false;
     static final boolean DEBUG_LRU = DEBUG_ALL || false;
     static final boolean DEBUG_MU = DEBUG_ALL || false;
-    static final boolean DEBUG_NETWORK = DEBUG_ALL || false;
     static final boolean DEBUG_OOM_ADJ = DEBUG_ALL || false;
     static final boolean DEBUG_PAUSE = DEBUG_ALL || false;
     static final boolean DEBUG_POWER = DEBUG_ALL || false;
@@ -108,7 +107,6 @@
     static final String POSTFIX_LOCKTASK = (APPEND_CATEGORY_NAME) ? "_LockTask" : "";
     static final String POSTFIX_LRU = (APPEND_CATEGORY_NAME) ? "_LRU" : "";
     static final String POSTFIX_MU = "_MU";
-    static final String POSTFIX_NETWORK = "_Network";
     static final String POSTFIX_OOM_ADJ = (APPEND_CATEGORY_NAME) ? "_OomAdj" : "";
     static final String POSTFIX_PAUSE = (APPEND_CATEGORY_NAME) ? "_Pause" : "";
     static final String POSTFIX_POWER = (APPEND_CATEGORY_NAME) ? "_Power" : "";
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 8656047..30b267f 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -42,9 +42,6 @@
 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
 import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
-import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
-import static android.net.NetworkPolicyManager.isProcStateAllowedWhileRestrictBackgroundOn;
-import static android.net.NetworkPolicyManager.UidStateWithSeqObserver;
 import static android.os.Build.VERSION_CODES.N;
 import static android.os.Process.PROC_CHAR;
 import static android.os.Process.PROC_OUT_LONG;
@@ -79,7 +76,6 @@
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LRU;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
-import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_NETWORK;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER;
@@ -109,7 +105,6 @@
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKTASK;
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LRU;
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
-import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_NETWORK;
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_OOM_ADJ;
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_POWER;
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESSES;
@@ -361,7 +356,6 @@
 import com.android.server.Watchdog;
 import com.android.server.am.ActivityStack.ActivityState;
 import com.android.server.firewall.IntentFirewall;
-import com.android.server.net.NetworkPolicyManagerService;
 import com.android.server.pm.Installer;
 import com.android.server.pm.Installer.InstallerException;
 import com.android.server.statusbar.StatusBarManagerInternal;
@@ -418,7 +412,6 @@
     private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
     private static final String TAG_LRU = TAG + POSTFIX_LRU;
     private static final String TAG_MU = TAG + POSTFIX_MU;
-    private static final String TAG_NETWORK = TAG + POSTFIX_NETWORK;
     private static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ;
     private static final String TAG_POWER = TAG + POSTFIX_POWER;
     private static final String TAG_PROCESS_OBSERVERS = TAG + POSTFIX_PROCESS_OBSERVERS;
@@ -605,8 +598,6 @@
     BroadcastStats mLastBroadcastStats;
     BroadcastStats mCurBroadcastStats;
 
-    private UidStateWithSeqObserver mUidStateWithSeqObserver;
-
     BroadcastQueue broadcastQueueForIntent(Intent intent) {
         final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
         if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST,
@@ -4231,26 +4222,6 @@
                     "*** Delivering " + N + " uid changes");
         }
 
-        if (mUidStateWithSeqObserver != null) {
-            final int registeredCallbackCount = mUidObservers.getRegisteredCallbackCount();
-            for (int i = 0; i < N; ++i) {
-                final UidRecord.ChangeItem item = mActiveUidChanges[i];
-                if (item.change != UidRecord.CHANGE_GONE
-                        && item.change != UidRecord.CHANGE_GONE_IDLE) {
-                    mUidStateWithSeqObserver.onUidStateChangedWithSeq(
-                            item.uid, item.processState, item.procStateSeq);
-                    if (VALIDATE_UID_STATES && registeredCallbackCount == 0) {
-                        UidRecord validateUid = mValidateUids.get(item.uid);
-                        if (validateUid == null) {
-                            validateUid = new UidRecord(item.uid);
-                            mValidateUids.put(item.uid, validateUid);
-                        }
-                        validateUid.curProcState = validateUid.setProcState = item.processState;
-                    }
-                }
-            }
-        }
-
         int i = mUidObservers.beginBroadcast();
         while (i > 0) {
             i--;
@@ -7723,7 +7694,7 @@
                             aspectRatio);
                     mStackSupervisor.moveActivityToPinnedStackLocked(r, "enterPictureInPictureMode",
                             bounds, true /* moveHomeStackToFront */);
-                    final ActivityStack stack = mStackSupervisor.getStack(PINNED_STACK_ID);
+                    final PinnedActivityStack stack = mStackSupervisor.getStack(PINNED_STACK_ID);
                     stack.setPictureInPictureAspectRatio(aspectRatio);
                     stack.setPictureInPictureActions(actions);
 
@@ -7777,9 +7748,9 @@
 
                 // Only update the saved args from the args that are set
                 r.pictureInPictureArgs.copyOnlySet(args);
-                final ActivityStack stack = r.getStack();
-                if (stack.getStackId() == PINNED_STACK_ID) {
+                if (r.getStack().getStackId() == PINNED_STACK_ID) {
                     // If the activity is already in picture-in-picture, update the pinned stack now
+                    final PinnedActivityStack stack = r.getStack();
                     stack.setPictureInPictureAspectRatio(r.pictureInPictureArgs.getAspectRatio());
                     stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
                 }
@@ -10341,7 +10312,7 @@
             synchronized (this) {
                 if (animate) {
                     if (stackId == PINNED_STACK_ID) {
-                        final ActivityStack pinnedStack =
+                        final PinnedActivityStack pinnedStack =
                                 mStackSupervisor.getStack(PINNED_STACK_ID);
                         pinnedStack.animateResizePinnedStack(bounds, animationDuration);
                     } else {
@@ -17627,16 +17598,11 @@
         }
     }
 
-    /**
-     * Returns sequence number associated with the current process state change if the service
-     * coming to the foreground needs to block for network before proceeding, otherwise
-     * {@link ActivityThread#INVALID_PROC_STATE_SEQ}.
-     */
     @Override
-    public long setServiceForeground(ComponentName className, IBinder token,
+    public void setServiceForeground(ComponentName className, IBinder token,
             int id, Notification notification, int flags) {
         synchronized(this) {
-            return mServices.setServiceForegroundLocked(className, token, id, notification, flags);
+            mServices.setServiceForegroundLocked(className, token, id, notification, flags);
         }
     }
 
@@ -21397,7 +21363,6 @@
         pendingChange.processState = uidRec != null
                 ? uidRec.setProcState : ActivityManager.PROCESS_STATE_NONEXISTENT;
         pendingChange.ephemeral = uidRec.ephemeral;
-        pendingChange.procStateSeq = uidRec.curProcStateSeq;
 
         // Directly update the power manager, since we sit on top of it and it is critical
         // it be kept in sync (so wake locks will be held as soon as appropriate).
@@ -21771,34 +21736,6 @@
             }
         }
 
-        for (int i = mActiveUids.size() - 1; i >= 0; --i) {
-            final UidRecord uidRec = mActiveUids.valueAt(i);
-            uidRec.shouldNotifyAppThreads = false;
-            if (uidRec.curProcState == uidRec.setProcState) {
-                continue;
-            }
-            final int newBlockState = getUidRecordBlockState(uidRec);
-            // Sequence no. associated with process state change will only be updated if the
-            // process is coming from background to foreground or vice versa.
-            if (newBlockState != uidRec.blockState) {
-                uidRec.blockState = newBlockState;
-                uidRec.curProcStateSeq++;
-                uidRec.appThreadListeners = null;
-                uidRec.shouldNotifyAppThreads = true;
-            }
-        }
-
-        for (int i = mLruProcesses.size() - 1; i >= 0; --i) {
-            final ProcessRecord app = mLruProcesses.get(i);
-            if (!app.killedByAm && app.thread != null && app.uidRecord.shouldNotifyAppThreads) {
-                try {
-                    app.thread.setBlockForNetworkState(app.uidRecord.blockState,
-                            app.uidRecord.curProcStateSeq);
-                } catch (RemoteException ignored) {
-                }
-            }
-        }
-
         mNumServiceProcs = mNewNumServiceProcs;
 
         // Now determine the memory trimming level of background processes.
@@ -23000,131 +22937,6 @@
                 updateOomAdjLocked(pr);
             }
         }
-
-        @Override
-        public void setUidStateWithSeqObserver(UidStateWithSeqObserver observer) {
-            synchronized (ActivityManagerService.this) {
-                mUidStateWithSeqObserver = observer;
-            }
-        }
-
-        @Override
-        public void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq) {
-            if (DEBUG_NETWORK) {
-                Slog.d(TAG_NETWORK, "Got update from NPMS uid: " + uid + " seq: " + procStateSeq);
-            }
-            synchronized (ActivityManagerService.this) {
-                final UidRecord record = mActiveUids.get(uid);
-                if (record == null) {
-                    if (DEBUG_NETWORK) {
-                        Slog.d(TAG_NETWORK, "No active uidRecord for uid: " + uid
-                                + "seq: " + procStateSeq);
-                    }
-                    return;
-                }
-                record.lastProcStateSeqWithUpdatedNetworkState = procStateSeq;
-                if (record.curProcStateSeq > procStateSeq) {
-                    if (DEBUG_NETWORK) {
-                        Slog.d(TAG_NETWORK, "Since the current procStateSeq is greater, the "
-                                + "listeners would already be notified when it is incremented.");
-                    }
-                    return;
-                }
-
-                if (record.appThreadListeners == null) {
-                    if (DEBUG_NETWORK) {
-                        Slog.d(TAG_NETWORK, "No app thread listeners for uid: " + uid
-                                + "seq: " + procStateSeq);
-                    }
-                    return;
-                }
-                for (int i = record.appThreadListeners.beginBroadcast() - 1; i >= 0; i--) {
-                    final IApplicationThread listener =
-                            record.appThreadListeners.getBroadcastItem(i);
-                    try {
-                        if (listener != null) {
-                            listener.notifyNetworkStateUpdated(procStateSeq);
-                        }
-                    } catch (RemoteException ignored) {
-                    }
-                }
-                record.appThreadListeners.finishBroadcast();
-                record.appThreadListeners = null;
-            }
-        }
-    }
-
-    @Override
-    public boolean registerNetworkRulesUpdateListener(IApplicationThread listener,
-            long procStateSeq) {
-        synchronized (this) {
-            final int uid = Binder.getCallingUid();
-            final UidRecord record = mActiveUids.get(uid);
-            if (record.lastProcStateSeqWithUpdatedNetworkState >= procStateSeq) {
-                if (DEBUG_NETWORK) {
-                    Slog.v(TAG_NETWORK, "Network state is already updated for seq: " + procStateSeq
-                            + ". No need to register listener for uid: " + uid);
-                }
-                return false;
-            }
-            if (record.curProcStateSeq > procStateSeq) {
-                if (DEBUG_NETWORK) {
-                    Slog.v(TAG_NETWORK, "Since the current procState is greater, there is no need "
-                            + " to register listeners for older seq numbers");
-                }
-            }
-            if (record.appThreadListeners == null) {
-                record.appThreadListeners = new RemoteCallbackList<>();
-            }
-            record.appThreadListeners.register(listener);
-            if (DEBUG_NETWORK) {
-                Slog.v(TAG_NETWORK, "Registered listener for uid: " + uid + " seq: " + procStateSeq);
-            }
-            return true;
-        }
-    }
-
-    private int getUidRecordBlockState(UidRecord uidRec) {
-        final boolean curStateAllowedWhileRestrictBackgroundOn
-                = isProcStateAllowedWhileRestrictBackgroundOn(uidRec.curProcState);
-        final boolean curStateAllowedWhileIdleOrPowerSaveMode
-                = isProcStateAllowedWhileIdleOrPowerSaveMode(uidRec.curProcState);
-
-        if (uidRec.setProcState == ActivityManager.PROCESS_STATE_UNKNOWN) {
-            if (uidRec.curProcState != ActivityManager.PROCESS_STATE_UNKNOWN &&
-                    (curStateAllowedWhileIdleOrPowerSaveMode
-                            || curStateAllowedWhileRestrictBackgroundOn)) {
-                return ActivityThread.NETWORK_STATE_BLOCK;
-            }
-            return ActivityThread.NETWORK_STATE_NO_CHANGE;
-        }
-
-        final boolean prevStateAllowedWhileRestrictBackgroundOn
-                = isProcStateAllowedWhileRestrictBackgroundOn(uidRec.setProcState);
-        final boolean prevStateAllowedWhileIdleOrPowerSaveMode
-                = isProcStateAllowedWhileIdleOrPowerSaveMode(uidRec.setProcState);
-
-        if (prevStateAllowedWhileIdleOrPowerSaveMode == curStateAllowedWhileIdleOrPowerSaveMode &&
-                prevStateAllowedWhileRestrictBackgroundOn ==
-                        curStateAllowedWhileRestrictBackgroundOn) {
-            return uidRec.blockState;
-        }
-
-        if (!prevStateAllowedWhileIdleOrPowerSaveMode && curStateAllowedWhileIdleOrPowerSaveMode) {
-            return ActivityThread.NETWORK_STATE_BLOCK;
-        } else if (!prevStateAllowedWhileRestrictBackgroundOn
-                && curStateAllowedWhileRestrictBackgroundOn) {
-            return ActivityThread.NETWORK_STATE_BLOCK;
-        }
-
-        if (prevStateAllowedWhileIdleOrPowerSaveMode && !curStateAllowedWhileIdleOrPowerSaveMode) {
-            return ActivityThread.NETWORK_STATE_UNBLOCK;
-        } else if (prevStateAllowedWhileRestrictBackgroundOn &&
-                !curStateAllowedWhileRestrictBackgroundOn) {
-            return ActivityThread.NETWORK_STATE_UNBLOCK;
-        }
-
-        return uidRec.blockState;
     }
 
     private final class SleepTokenImpl extends SleepToken {
diff --git a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
index 80df26b..aaad12c 100644
--- a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
+++ b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
@@ -240,6 +240,8 @@
                     return runSupportsSplitScreenMultiwindow(pw);
                 case "update-appinfo":
                     return runUpdateApplicationInfo(pw);
+                case "no-home-screen":
+                    return runNoHomeScreen(pw);
                 default:
                     return handleDefaultCommands(cmd);
             }
@@ -2386,6 +2388,15 @@
         return 0;
     }
 
+    int runNoHomeScreen(PrintWriter pw) throws RemoteException {
+        final Resources res = getResources(pw);
+        if (res == null) {
+            return -1;
+        }
+        pw.println(res.getBoolean(com.android.internal.R.bool.config_noHomeScreen));
+        return 0;
+    }
+
     private Resources getResources(PrintWriter pw) throws RemoteException {
         // system resources does not contain all the device configuration, construct it manually.
         Configuration config = mInterface.getConfiguration();
diff --git a/services/core/java/com/android/server/am/ActivityRecord.java b/services/core/java/com/android/server/am/ActivityRecord.java
index 6f89cf2..aef429e 100644
--- a/services/core/java/com/android/server/am/ActivityRecord.java
+++ b/services/core/java/com/android/server/am/ActivityRecord.java
@@ -880,8 +880,8 @@
     /**
      * @return Stack value from current task, null if there is no task.
      */
-    ActivityStack getStack() {
-        return task != null ? task.getStack() : null;
+    <T extends ActivityStack> T getStack() {
+        return task != null ? (T) task.getStack() : null;
     }
 
     boolean changeWindowTranslucency(boolean toOpaque) {
diff --git a/services/core/java/com/android/server/am/ActivityStack.java b/services/core/java/com/android/server/am/ActivityStack.java
index b948c15..7f7caff 100644
--- a/services/core/java/com/android/server/am/ActivityStack.java
+++ b/services/core/java/com/android/server/am/ActivityStack.java
@@ -84,7 +84,6 @@
 import android.app.ActivityOptions;
 import android.app.AppGlobals;
 import android.app.IActivityController;
-import android.app.RemoteAction;
 import android.app.ResultInfo;
 import android.content.ComponentName;
 import android.content.Intent;
@@ -135,7 +134,8 @@
 /**
  * State and management of a single stack of activities.
  */
-final class ActivityStack extends ConfigurationContainer implements StackWindowListener {
+class ActivityStack<T extends StackWindowController> extends ConfigurationContainer
+        implements StackWindowListener {
 
     private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStack" : TAG_AM;
     private static final String TAG_ADD_REMOVE = TAG + POSTFIX_ADD_REMOVE;
@@ -247,7 +247,7 @@
 
     final ActivityManagerService mService;
     private final WindowManagerService mWindowManager;
-    private StackWindowController mWindowContainerController;
+    T mWindowContainerController;
     private final RecentTasks mRecentTasks;
 
     /**
@@ -462,14 +462,18 @@
                 ? new LaunchingTaskPositioner() : null;
         final ActivityStackSupervisor.ActivityDisplay display = mActivityContainer.mActivityDisplay;
         mTmpRect2.setEmpty();
-        mWindowContainerController = new StackWindowController(mStackId, this,
-                display.mDisplayId, onTop, mTmpRect2);
+        mWindowContainerController = createStackWindowController(display.mDisplayId, onTop,
+                mTmpRect2);
         activityContainer.mStack = this;
         mStackSupervisor.mActivityContainers.put(mStackId, activityContainer);
         postAddToDisplay(display, mTmpRect2.isEmpty() ? null : mTmpRect2, onTop);
     }
 
-    StackWindowController getWindowContainerController() {
+    T createStackWindowController(int displayId, boolean onTop, Rect outBounds) {
+        return (T) new StackWindowController(mStackId, this, displayId, onTop, outBounds);
+    }
+
+    T getWindowContainerController() {
         return mWindowContainerController;
     }
 
@@ -540,18 +544,6 @@
         mActivityContainer.mActivityDisplay.mDisplay.getSize(out);
     }
 
-    void animateResizePinnedStack(Rect bounds, int animationDuration) {
-        mWindowContainerController.animateResizePinnedStack(bounds, animationDuration);
-    }
-
-    void setPictureInPictureAspectRatio(float aspectRatio) {
-        mWindowContainerController.setPictureInPictureAspectRatio(aspectRatio);
-    }
-
-    void setPictureInPictureActions(List<RemoteAction> actions) {
-        mWindowContainerController.setPictureInPictureActions(actions);
-    }
-
     void getStackDockedModeBounds(Rect outBounds, Rect outTempBounds, Rect outTempInsetBounds,
             boolean ignoreVisibility) {
         mWindowContainerController.getStackDockedModeBounds(outBounds, outTempBounds,
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
index 7ceeff8..1e33bb9 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
@@ -120,7 +120,6 @@
 import android.content.pm.ResolveInfo;
 import android.content.pm.UserInfo;
 import android.content.res.Configuration;
-import android.graphics.Point;
 import android.graphics.Rect;
 import android.hardware.display.DisplayManager;
 import android.hardware.display.DisplayManager.DisplayListener;
@@ -153,7 +152,6 @@
 import android.service.voice.IVoiceInteractionSession;
 import android.util.ArrayMap;
 import android.util.ArraySet;
-import android.util.DisplayMetrics;
 import android.util.EventLog;
 import android.util.IntArray;
 import android.util.Slog;
@@ -2037,19 +2035,20 @@
                 || mService.mSupportsFreeformWindowManagement;
     }
 
-    ActivityStack getStack(int stackId) {
+    protected <T extends ActivityStack> T getStack(int stackId) {
         return getStack(stackId, !CREATE_IF_NEEDED, !ON_TOP);
     }
 
-    ActivityStack getStack(int stackId, boolean createStaticStackIfNeeded, boolean createOnTop) {
+    protected <T extends ActivityStack> T getStack(int stackId, boolean createStaticStackIfNeeded,
+            boolean createOnTop) {
         final ActivityContainer activityContainer = mActivityContainers.get(stackId);
         if (activityContainer != null) {
-            return activityContainer.mStack;
+            return (T) activityContainer.mStack;
         }
         if (!createStaticStackIfNeeded || !StackId.isStaticStack(stackId)) {
             return null;
         }
-        return createStackOnDisplay(stackId, DEFAULT_DISPLAY, createOnTop);
+        return (T) createStackOnDisplay(stackId, DEFAULT_DISPLAY, createOnTop);
     }
 
     /**
@@ -2856,7 +2855,7 @@
 
         mWindowManager.deferSurfaceLayout();
         // Need to make sure the pinned stack exist so we can resize it below...
-        final ActivityStack stack = getStack(PINNED_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
+        final PinnedActivityStack stack = getStack(PINNED_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
 
         try {
             final TaskRecord task = r.task;
@@ -2906,7 +2905,7 @@
         ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
         resumeFocusedStackTopActivityLocked();
 
-        stack.animateResizePinnedStack(bounds, -1);
+        stack.animateResizePinnedStack(bounds, -1 /* animationDuration */);
         mService.mTaskChangeNotificationController.notifyActivityPinned();
     }
 
@@ -4367,7 +4366,14 @@
             synchronized (mService) {
                 mStackId = stackId;
                 mActivityDisplay = activityDisplay;
-                new ActivityStack(this, mRecentTasks, onTop);
+                switch (mStackId) {
+                    case PINNED_STACK_ID:
+                        new PinnedActivityStack(this, mRecentTasks, onTop);
+                        break;
+                    default:
+                        new ActivityStack(this, mRecentTasks, onTop);
+                        break;
+                }
                 mIdString = "ActivtyContainer{" + mStackId + "}";
                 if (DEBUG_STACK) Slog.d(TAG_STACK, "Creating " + this);
             }
diff --git a/services/core/java/com/android/server/am/CoreSettingsObserver.java b/services/core/java/com/android/server/am/CoreSettingsObserver.java
index 62c3f4a..73a17c6 100644
--- a/services/core/java/com/android/server/am/CoreSettingsObserver.java
+++ b/services/core/java/com/android/server/am/CoreSettingsObserver.java
@@ -49,7 +49,6 @@
         // add other system settings here...
 
         sGlobalSettingToTypeMap.put(Settings.Global.DEBUG_VIEW_ATTRIBUTES, int.class);
-        sGlobalSettingToTypeMap.put(Settings.Global.WAIT_FOR_NETWORK_TIMEOUT_MS, long.class);
         // add other global settings here...
     }
 
@@ -57,8 +56,6 @@
 
     private final ActivityManagerService mActivityManagerService;
 
-    private static final long WAIT_FOR_NETWORK_TIMEOUT_DEFAULT_MS = 0; // 0 sec
-
     public CoreSettingsObserver(ActivityManagerService activityManagerService) {
         super(activityManagerService.mHandler);
         mActivityManagerService = activityManagerService;
@@ -146,13 +143,7 @@
                 } else if (map == sSystemSettingToTypeMap) {
                     value = Settings.System.getLong(context.getContentResolver(), setting, 0);
                 } else {
-                    // TODO: remove this conditional and set the default in settings provider.
-                    if (Settings.Global.WAIT_FOR_NETWORK_TIMEOUT_MS.equals(setting)) {
-                        value = Settings.Global.getLong(context.getContentResolver(), setting,
-                                WAIT_FOR_NETWORK_TIMEOUT_DEFAULT_MS);
-                    } else {
-                        value = Settings.Global.getLong(context.getContentResolver(), setting, 0);
-                    }
+                    value = Settings.Global.getLong(context.getContentResolver(), setting, 0);
                 }
                 snapshot.putLong(setting, value);
             }
diff --git a/services/core/java/com/android/server/am/PinnedActivityStack.java b/services/core/java/com/android/server/am/PinnedActivityStack.java
new file mode 100644
index 0000000..aa7ab15
--- /dev/null
+++ b/services/core/java/com/android/server/am/PinnedActivityStack.java
@@ -0,0 +1,55 @@
+/*
+ * 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.server.am;
+
+import android.app.RemoteAction;
+import android.graphics.Rect;
+
+import com.android.server.am.ActivityStackSupervisor.ActivityContainer;
+import com.android.server.wm.PinnedStackWindowController;
+import com.android.server.wm.StackWindowController;
+
+import java.util.List;
+
+/**
+ * State and management of the pinned stack of activities.
+ */
+class PinnedActivityStack extends ActivityStack<PinnedStackWindowController> {
+
+    PinnedActivityStack(ActivityContainer activityContainer,
+            RecentTasks recentTasks, boolean onTop) {
+        super(activityContainer, recentTasks, onTop);
+    }
+
+    @Override
+    PinnedStackWindowController createStackWindowController(int displayId, boolean onTop,
+            Rect outBounds) {
+        return new PinnedStackWindowController(mStackId, this, displayId, onTop, outBounds);
+    }
+
+    void animateResizePinnedStack(Rect bounds, int animationDuration) {
+        getWindowContainerController().animateResizePinnedStack(bounds, animationDuration);
+    }
+
+    void setPictureInPictureAspectRatio(float aspectRatio) {
+        getWindowContainerController().setPictureInPictureAspectRatio(aspectRatio);
+    }
+
+    void setPictureInPictureActions(List<RemoteAction> actions) {
+        getWindowContainerController().setPictureInPictureActions(actions);
+    }
+}
diff --git a/services/core/java/com/android/server/am/UidRecord.java b/services/core/java/com/android/server/am/UidRecord.java
index 1e16bc9..302f628 100644
--- a/services/core/java/com/android/server/am/UidRecord.java
+++ b/services/core/java/com/android/server/am/UidRecord.java
@@ -17,12 +17,8 @@
 package com.android.server.am;
 
 import android.app.ActivityManager;
-import android.app.ActivityThread;
-import android.app.IApplicationThread;
-import android.os.RemoteCallbackList;
 import android.os.SystemClock;
 import android.os.UserHandle;
-import android.util.DebugUtils;
 import android.util.TimeUtils;
 
 /**
@@ -38,27 +34,6 @@
     boolean setWhitelist;
     boolean idle;
     int numProcs;
-    /**
-     * Seq no. associated with the current process state change (from background to foreground or
-     * vice versa).
-     */
-    long curProcStateSeq;
-    /**
-     * Latest seq number for which NetworkPolicyManagerService notified ActivityManagerService that
-     * network policy rules are updated.
-     */
-    long lastProcStateSeqWithUpdatedNetworkState;
-    /**
-     * Current block state indicating whether components in the process corresponding to this
-     * uidRecord needs to block for network or unblock or if there is no change.
-     * value will be one of {@link ActivityThread#NETWORK_STATE_BLOCK},
-     * {@link ActivityThread#NETWORK_STATE_UNBLOCK}, {@link ActivityThread#NETWORK_STATE_NO_CHANGE}.
-     */
-    int blockState;
-    /** Indicates whether app threads need be notified of the current blockState change. */
-    boolean shouldNotifyAppThreads;
-    /** Listeners waiting for the network policy rules to get updated. */
-    RemoteCallbackList<IApplicationThread> appThreadListeners;
 
     static final int CHANGE_PROCSTATE = 0;
     static final int CHANGE_GONE = 1;
@@ -72,7 +47,6 @@
         int change;
         int processState;
         boolean ephemeral;
-        long procStateSeq;
     }
 
     ChangeItem pendingChange;
@@ -109,14 +83,6 @@
         }
         sb.append(" procs:");
         sb.append(numProcs);
-        sb.append(" procStateSeq:");
-        sb.append(curProcStateSeq);
-        sb.append(" lastProcStateSeqWithUpdatedNetworkState:");
-        sb.append(lastProcStateSeqWithUpdatedNetworkState);
-        sb.append(" blockState:");
-        sb.append(DebugUtils.valueToString(ActivityThread.class, "NETWORK_STATE_", blockState));
-        sb.append(" shouldNotifyAppThreads:");
-        sb.append(shouldNotifyAppThreads);
         sb.append("}");
         return sb.toString();
     }
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index 5b3495f..79b99a3 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -6518,35 +6518,22 @@
         return mRecordMonitor.getActiveRecordingConfigurations();
     }
 
-    public void disableRingtoneSync() {
+    public void disableRingtoneSync(final int userId) {
         final int callingUserId = UserHandle.getCallingUserId();
+        if (callingUserId != userId) {
+            mContext.enforceCallingOrSelfPermission(Manifest.permission.INTERACT_ACROSS_USERS_FULL,
+                    "disable sound settings syncing for another profile");
+        }
         final long token = Binder.clearCallingIdentity();
         try {
-            UserManager userManager = UserManager.get(mContext);
-
-            // Disable the sync setting
-            Settings.Secure.putIntForUser(mContentResolver,
-                    Settings.Secure.SYNC_PARENT_SOUNDS, 0 /* false */, callingUserId);
-
-            UserInfo parentInfo = userManager.getProfileParent(callingUserId);
-            if (parentInfo != null && parentInfo.id != callingUserId) {
-                // This is a managed profile, so we clone the ringtones from the parent profile
-                cloneRingtoneSetting(callingUserId, parentInfo.id, Settings.System.RINGTONE);
-                cloneRingtoneSetting(callingUserId, parentInfo.id,
-                        Settings.System.NOTIFICATION_SOUND);
-                cloneRingtoneSetting(callingUserId, parentInfo.id, Settings.System.ALARM_ALERT);
-            }
+            // Disable the sync setting so the profile uses its own sound settings.
+            Settings.Secure.putIntForUser(mContentResolver, Settings.Secure.SYNC_PARENT_SOUNDS,
+                    0 /* false */, userId);
         } finally {
             Binder.restoreCallingIdentity(token);
         }
     }
 
-    private void cloneRingtoneSetting(int userId, int parentId, String ringtoneSetting) {
-        String parentSetting = Settings.System.getStringForUser(mContentResolver, ringtoneSetting,
-                parentId);
-        Settings.System.putStringForUser(mContentResolver, ringtoneSetting, parentSetting, userId);
-    }
-
     //======================
     // Audio playback notification
     //======================
diff --git a/services/core/java/com/android/server/audio/PlaybackActivityMonitor.java b/services/core/java/com/android/server/audio/PlaybackActivityMonitor.java
index 1f64b65..e8ff510 100644
--- a/services/core/java/com/android/server/audio/PlaybackActivityMonitor.java
+++ b/services/core/java/com/android/server/audio/PlaybackActivityMonitor.java
@@ -47,6 +47,7 @@
         implements AudioPlaybackConfiguration.PlayerDeathMonitor, PlayerFocusEnforcer {
 
     public final static String TAG = "AudioService.PlaybackActivityMonitor";
+
     private final static boolean DEBUG = false;
     private final static int VOLUME_SHAPER_SYSTEM_DUCK_ID = 1;
 
diff --git a/services/core/java/com/android/server/display/VirtualDisplayAdapter.java b/services/core/java/com/android/server/display/VirtualDisplayAdapter.java
index 74e025d..5149933 100644
--- a/services/core/java/com/android/server/display/VirtualDisplayAdapter.java
+++ b/services/core/java/com/android/server/display/VirtualDisplayAdapter.java
@@ -149,13 +149,7 @@
     }
 
     private void handleBinderDiedLocked(IBinder appToken) {
-        VirtualDisplayDevice device = mVirtualDisplayDevices.remove(appToken);
-        if (device != null) {
-            Slog.i(TAG, "Virtual display device released because application token died: "
-                    + device.mOwnerPackageName);
-            device.destroyLocked(false);
-            sendDisplayDeviceEventLocked(device, DISPLAY_DEVICE_EVENT_REMOVED);
-        }
+        mVirtualDisplayDevices.remove(appToken);
     }
 
     private void handleMediaProjectionStoppedLocked(IBinder appToken) {
@@ -216,6 +210,10 @@
         public void binderDied() {
             synchronized (getSyncRoot()) {
                 handleBinderDiedLocked(mAppToken);
+                Slog.i(TAG, "Virtual display device released because application token died: "
+                    + mOwnerPackageName);
+                destroyLocked(false);
+                sendDisplayDeviceEventLocked(this, DISPLAY_DEVICE_EVENT_REMOVED);
             }
         }
 
diff --git a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
index 91c9316..ac3a025 100644
--- a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
+++ b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
@@ -23,7 +23,6 @@
 import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
 import static android.Manifest.permission.READ_PHONE_STATE;
 import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
-import static android.app.ActivityThread.INVALID_PROC_STATE_SEQ;
 import static android.content.Intent.ACTION_PACKAGE_ADDED;
 import static android.content.Intent.ACTION_UID_REMOVED;
 import static android.content.Intent.ACTION_USER_ADDED;
@@ -54,15 +53,11 @@
 import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
 import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
 import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
-import static android.net.NetworkPolicyManager.RULE_INVALID;
 import static android.net.NetworkPolicyManager.RULE_NONE;
 import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
 import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
 import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
-import static android.net.NetworkPolicyManager.UidStateWithSeqObserver;
 import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
-import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
-import static android.net.NetworkPolicyManager.isProcStateAllowedWhileRestrictBackgroundOn;
 import static android.net.NetworkPolicyManager.uidPoliciesToString;
 import static android.net.NetworkPolicyManager.uidRulesToString;
 import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
@@ -99,7 +94,6 @@
 import android.annotation.IntDef;
 import android.annotation.Nullable;
 import android.app.ActivityManager;
-import android.app.ActivityManagerInternal;
 import android.app.AppGlobals;
 import android.app.AppOpsManager;
 import android.app.IActivityManager;
@@ -129,7 +123,6 @@
 import android.net.NetworkIdentity;
 import android.net.NetworkInfo;
 import android.net.NetworkPolicy;
-import android.net.NetworkPolicyManager;
 import android.net.NetworkQuotaInfo;
 import android.net.NetworkState;
 import android.net.NetworkTemplate;
@@ -137,7 +130,6 @@
 import android.net.wifi.WifiInfo;
 import android.net.wifi.WifiManager;
 import android.os.Binder;
-import android.os.Debug;
 import android.os.Environment;
 import android.os.Handler;
 import android.os.HandlerThread;
@@ -169,10 +161,8 @@
 import android.util.NtpTrustedTime;
 import android.util.Pair;
 import android.util.Slog;
-import android.util.SparseArray;
 import android.util.SparseBooleanArray;
 import android.util.SparseIntArray;
-import android.util.SparseLongArray;
 import android.util.TrustedTime;
 import android.util.Xml;
 
@@ -220,16 +210,14 @@
  * enforcement.
  *
  * <p>
- * This class uses 4 locks to synchronize state:
+ * This class uses 2-3 locks to synchronize state:
  * <ul>
  * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
  * rules).
  * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
  * as network policies).
- * <li>{@code mDispatchedThirdLock}: used to guard state related to process state sequence numbers
- * of uids which are currently blocked waiting for network.
- * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that both locks
- * {@code mUidRulesFirstLock} and {@code mNetworkPoliciesSecondLock} must be held.
+ * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
+ * must be held.
  * </ul>
  *
  * <p>
@@ -237,11 +225,8 @@
  * <ul>
  * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
  * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
- * <li>{@code DL()}: require the "Dispatched" lock ({@code mDispatchedThirdLock}).
- * <li>{@code AL()}: require both locks {@code mUidRulesFirstLock} and
- * {@code mNetworkPoliciesSecondLock}.
- * When multiple locks are needed, they must be obtained in order ({@code mUidRulesFirstLock}
- * first, then {@code mNetworkPoliciesSecondLock}, then {@code mDispatchedThirdLock}, etc..
+ * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
+ * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
  * </ul>
  */
 public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
@@ -328,27 +313,6 @@
     // See main javadoc for instructions on how to use these locks.
     final Object mUidRulesFirstLock = new Object();
     final Object mNetworkPoliciesSecondLock = new Object();
-    final Object mDispatchedThirdLock = new Object();
-
-    @GuardedBy("mDispatchedThirdLock")
-    private final SparseLongArray mLastHandledProcStateSeq = new SparseLongArray();
-
-    /**
-     * Used for tracking whether the updated uid and firewall rules have been dispatched to
-     * ConnectivityService and NetworkManagementService respectively.
-     *
-     * SparseIntArray: uid -> dispatch flags (one or more combinations of {@link #FLAG_NONE},
-     * {@link #FLAG_UID_RULES_DISPATCHED}, {@link #FLAG_FIREWALL_RULES_DISPATCHED} and
-     * {@link #FLAG_ALL_RULES_DISPATCHED}).
-     */
-    @GuardedBy("mDispatchedThirdLock")
-    private final SparseIntArray mDispatchFlagsForCurProcStateSeq = new SparseIntArray();
-
-    private final int FLAG_NONE = 0;
-    private final int FLAG_UID_RULES_DISPATCHED = 1 << 0;
-    private final int FLAG_FIREWALL_RULES_DISPATCHED = 1 << 1;
-    private final int FLAG_ALL_RULES_DISPATCHED =
-            (FLAG_UID_RULES_DISPATCHED | FLAG_FIREWALL_RULES_DISPATCHED);
 
     @GuardedBy("allLocks") volatile boolean mSystemReady;
 
@@ -443,8 +407,6 @@
 
     private final IPackageManager mIPm;
 
-    private ActivityManagerInternal mActivityManagerInternal;
-
 
     // TODO: keep whitelist of system-critical services that should never have
     // rules enforced, such as system, phone, and radio UIDs.
@@ -655,16 +617,13 @@
 
             try {
                 mActivityManager.registerUidObserver(mUidObserver,
-                        ActivityManager.UID_OBSERVER_GONE,
+                        ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
                         ActivityManager.PROCESS_STATE_UNKNOWN, null);
                 mNetworkManager.registerObserver(mAlertObserver);
             } catch (RemoteException e) {
                 // ignored; both services live in system_server
             }
 
-            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
-            mActivityManagerInternal.setUidStateWithSeqObserver(mUidStateWithSeqObserver);
-
             // listen for changes to power save whitelist
             final IntentFilter whitelistFilter = new IntentFilter(
                     PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
@@ -746,24 +705,17 @@
         }
     }
 
-    final private UidStateWithSeqObserver mUidStateWithSeqObserver = new UidStateWithSeqObserver() {
-        @Override
-        public void onUidStateChangedWithSeq(int uid, int procState, long procStateSeq) {
+    final private IUidObserver mUidObserver = new IUidObserver.Stub() {
+        @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
             Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
             try {
-                final long effectiveProcStateSeq = getEffectiveProcStateSeq(uid, procStateSeq);
                 synchronized (mUidRulesFirstLock) {
-                    updateUidStateUL(uid, procState, effectiveProcStateSeq);
+                    updateUidStateUL(uid, procState);
                 }
             } finally {
                 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
             }
         }
-    };
-
-    final private IUidObserver mUidObserver = new IUidObserver.Stub() {
-        @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
-        }
 
         @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
             synchronized (mUidRulesFirstLock) {
@@ -1890,7 +1842,7 @@
         }
 
         // uid policy changed, recompute rules and persist policy.
-        updateRulesForDataUsageRestrictionsUL(uid, true);
+        updateRulesForDataUsageRestrictionsUL(uid);
         if (persist) {
             synchronized (mNetworkPoliciesSecondLock) {
                 writePolicyAL();
@@ -2489,7 +2441,7 @@
 
     private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
         final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
-        return isProcStateAllowedWhileRestrictBackgroundOn(procState);
+        return isProcStateAllowedWhileOnRestrictBackground(procState);
     }
 
     private boolean isUidForegroundOnRestrictPowerUL(int uid) {
@@ -2507,50 +2459,26 @@
      * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
      * {@link #updateRulesForPowerRestrictionsUL(int)}
      */
-    private void updateUidStateUL(int uid, int uidState, long procStateSeq) {
+    private void updateUidStateUL(int uid, int uidState) {
         Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
         try {
             final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
             if (oldUidState != uidState) {
                 // state changed, push updated rules
                 mUidState.put(uid, uidState);
-                if (procStateSeq != INVALID_PROC_STATE_SEQ) {
-                    int updatedUidRules = RULE_INVALID;
-                    ReturnStatus status = updateRestrictBackgroundRulesOnUidStatusChangedUL(
-                            uid, oldUidState, uidState, false);
-                    if (status != null && status.mNeedToNotify) {
-                        updatedUidRules = status.mNewUidRules;
+                updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
+                if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
+                        != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
+                    if (isUidIdle(uid)) {
+                        updateRuleForAppIdleUL(uid);
                     }
-                    final boolean procStateChangedAllowedWhileIdleOrPowerSaveMode =
-                            isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
-                                    != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState);
-                    if (procStateChangedAllowedWhileIdleOrPowerSaveMode) {
-                        status = updateRulesForPowerRestrictionsUL(uid, false);
-                        if (status != null && status.mNeedToNotify) {
-                            updatedUidRules = status.mNewUidRules;
-                        }
+                    if (mDeviceIdleMode) {
+                        updateRuleForDeviceIdleUL(uid);
                     }
-                    // TODO: We can avoid this if the rules are not changed. But since dispatching
-                    // to ConnectivityService is currently asynchronous, we need this to make sure
-                    // any previous the msg_rules_changes have been handled. Optimize this once
-                    // dispatching from NPMS to ConnectivityService is made synchronous.
-                    mHandler.obtainMessage(MSG_RULES_CHANGED, uid, updatedUidRules,
-                            procStateSeq).sendToTarget();
-                    if (procStateChangedAllowedWhileIdleOrPowerSaveMode) {
-                        if (isUidIdle(uid)) {
-                            updateRuleForAppIdleUL(uid);
-                        }
-                        if (mDeviceIdleMode) {
-                            updateRuleForDeviceIdleUL(uid);
-                        }
-                        if (mRestrictPower) {
-                            updateRuleForRestrictPowerUL(uid);
-                        }
+                    if (mRestrictPower) {
+                        updateRuleForRestrictPowerUL(uid);
                     }
-                    synchronized (mDispatchedThirdLock) {
-                        setDispatchedFlagDL(uid, procStateSeq, FLAG_FIREWALL_RULES_DISPATCHED);
-                        checkAndNotifyDL(uid, procStateSeq);
-                    }
+                    updateRulesForPowerRestrictionsUL(uid);
                 }
                 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
             }
@@ -2559,61 +2487,6 @@
         }
     }
 
-    /**
-     * Returns {@link android.app.ActivityThread#INVALID_PROC_STATE_SEQ} if acting on
-     * {@param procStateSeq} leads to an invalid state, otherwise update global state and return
-     * {@param procStateSeq}.
-     */
-    private long getEffectiveProcStateSeq(int uid, long procStateSeq) {
-        synchronized (mDispatchedThirdLock) {
-            final long lastHandledProcStateSeq = mLastHandledProcStateSeq.get(uid);
-            if (procStateSeq < lastHandledProcStateSeq) {
-                Slog.wtf(TAG, "procStateSeq from AMS should never go down, procStateSeq: "
-                        + procStateSeq + " lastHandledProcStateSeq: " + lastHandledProcStateSeq
-                        + " uid: " + uid);
-                return INVALID_PROC_STATE_SEQ;
-            }
-            if (procStateSeq == lastHandledProcStateSeq) {
-                if (LOGD) {
-                    Slog.d(TAG, "procStateSeq: " + procStateSeq + " is not changed, so process is "
-                            + "not jumping from background to foreground or vice versa. "
-                            + "uid: " + uid);
-                }
-                return INVALID_PROC_STATE_SEQ;
-            }
-            mLastHandledProcStateSeq.put(uid, procStateSeq);
-            mDispatchFlagsForCurProcStateSeq.put(uid, 0);
-            return procStateSeq;
-        }
-    }
-
-    /**
-     * Update dispatch flags to include {@param flag}.
-     */
-    private void setDispatchedFlagDL(int uid, long procStateSeq, int flag) {
-        int dispatchedFlag = mDispatchFlagsForCurProcStateSeq.get(uid);
-        dispatchedFlag |= flag;
-        mDispatchFlagsForCurProcStateSeq.put(uid, dispatchedFlag);
-    }
-
-    /**
-     * Check whether uid and firewall rules are dispatched to ConnectivityService and
-     * NetworkManagementService respectively, if so notify ActivityManagerService that network
-     * rules are updated.
-     */
-    private void checkAndNotifyDL(int uid, long procStateSeq) {
-        synchronized (mDispatchedThirdLock) {
-            final int dispatchedFlags = mDispatchFlagsForCurProcStateSeq.get(uid);
-            if (dispatchedFlags == FLAG_ALL_RULES_DISPATCHED) {
-                if (LOGD) {
-                    Slog.d(TAG, "Notifying AMS that network rules are updated for uid: " + uid
-                            + " seq: " + procStateSeq + " callers: " + Debug.getCallers(3));
-                }
-                mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
-            }
-        }
-    }
-
     private void removeUidStateUL(int uid) {
         final int index = mUidState.indexOfKey(uid);
         if (index >= 0) {
@@ -2621,21 +2494,17 @@
             mUidState.removeAt(index);
             if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
                 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
-                        ActivityManager.PROCESS_STATE_CACHED_EMPTY, true);
+                        ActivityManager.PROCESS_STATE_CACHED_EMPTY);
                 if (mDeviceIdleMode) {
                     updateRuleForDeviceIdleUL(uid);
                 }
                 if (mRestrictPower) {
                     updateRuleForRestrictPowerUL(uid);
                 }
-                updateRulesForPowerRestrictionsUL(uid, true);
+                updateRulesForPowerRestrictionsUL(uid);
                 updateNetworkStats(uid, false);
             }
         }
-        synchronized (mDispatchedThirdLock) {
-            mLastHandledProcStateSeq.delete(uid);
-            mDispatchFlagsForCurProcStateSeq.delete(uid);
-        }
     }
 
     // adjust stats accounting based on foreground status
@@ -2647,16 +2516,23 @@
         }
     }
 
-    private ReturnStatus updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
-            int newUidState, boolean notify) {
+    private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
+            int newUidState) {
         final boolean oldForeground =
-                isProcStateAllowedWhileRestrictBackgroundOn(oldUidState);
+                isProcStateAllowedWhileOnRestrictBackground(oldUidState);
         final boolean newForeground =
-                isProcStateAllowedWhileRestrictBackgroundOn(newUidState);
+                isProcStateAllowedWhileOnRestrictBackground(newUidState);
         if (oldForeground != newForeground) {
-            return updateRulesForDataUsageRestrictionsUL(uid, notify);
+            updateRulesForDataUsageRestrictionsUL(uid);
         }
-        return null;
+    }
+
+    static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
+        return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
+    }
+
+    static boolean isProcStateAllowedWhileOnRestrictBackground(int procState) {
+        return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
     }
 
     void updateRulesForPowerSaveUL() {
@@ -2805,7 +2681,7 @@
                 // Skip if it had no restrictions to begin with
                 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
             }
-            updateRulesForPowerRestrictionsUL(uid, oldRules, paroled, true);
+            updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
         }
     }
 
@@ -2885,10 +2761,10 @@
                     final int uid = UserHandle.getUid(user.id, app.uid);
                     switch (type) {
                         case TYPE_RESTRICT_BACKGROUND:
-                            updateRulesForDataUsageRestrictionsUL(uid, true);
+                            updateRulesForDataUsageRestrictionsUL(uid);
                             break;
                         case TYPE_RESTRICT_POWER:
-                            updateRulesForPowerRestrictionsUL(uid, true);
+                            updateRulesForPowerRestrictionsUL(uid);
                             break;
                         default:
                             Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
@@ -2914,7 +2790,7 @@
                 updateRuleForDeviceIdleUL(uid);
                 updateRuleForRestrictPowerUL(uid);
                 // Update internal rules.
-                updateRulesForPowerRestrictionsUL(uid, true);
+                updateRulesForPowerRestrictionsUL(uid);
             }
         }
     }
@@ -2978,10 +2854,6 @@
         mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
         mPowerSaveWhitelistAppIds.delete(uid);
         mPowerSaveTempWhitelistAppIds.delete(uid);
-        synchronized (mDispatchedThirdLock) {
-            mLastHandledProcStateSeq.delete(uid);
-            mDispatchFlagsForCurProcStateSeq.delete(uid);
-        }
 
         // ...then update iptables asynchronously.
         mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
@@ -3007,10 +2879,10 @@
         updateRuleForRestrictPowerUL(uid);
 
         // Update internal state for power-related modes.
-        updateRulesForPowerRestrictionsUL(uid, true);
+        updateRulesForPowerRestrictionsUL(uid);
 
         // Update firewall and internal rules for Data Saver Mode.
-        updateRulesForDataUsageRestrictionsUL(uid, true);
+        updateRulesForDataUsageRestrictionsUL(uid);
     }
 
     /**
@@ -3051,16 +2923,11 @@
      *
      * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
      *
-     * @param uid The uid for which the rules have to be updated.
-     * @param notify Indicates whether to notify network policy listeners if the rules are updated.
-     *
-     * @return ReturnStatus includes new updated rules and whether network policy listeners
-     *         (INetworkPolicyListener) need to be notified.
      */
-    private ReturnStatus updateRulesForDataUsageRestrictionsUL(int uid, boolean notify) {
+    private void updateRulesForDataUsageRestrictionsUL(int uid) {
         if (!isUidValidForWhitelistRules(uid)) {
             if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
-            return new ReturnStatus(false, RULE_NONE);
+            return;
         }
 
         final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
@@ -3155,12 +3022,9 @@
                         + ", oldRule=" + uidRulesToString(oldUidRules));
             }
 
-            if (notify) {
-                mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
-            }
-            return new ReturnStatus(true, newUidRules);
+            // Dispatch changed rule to existing listeners.
+            mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
         }
-        return new ReturnStatus(false, newUidRules);
     }
 
     /**
@@ -3181,18 +3045,16 @@
      * <p>
      * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
      */
-    private ReturnStatus updateRulesForPowerRestrictionsUL(int uid, boolean notify) {
+    private void updateRulesForPowerRestrictionsUL(int uid) {
         final int oldUidRules = mUidRules.get(uid, RULE_NONE);
 
-        final ReturnStatus status = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false,
-                notify);
+        final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
 
-        if (status.mNewUidRules == RULE_NONE) {
+        if (newUidRules == RULE_NONE) {
             mUidRules.delete(uid);
         } else {
-            mUidRules.put(uid, status.mNewUidRules);
+            mUidRules.put(uid, newUidRules);
         }
-        return status;
     }
 
     /**
@@ -3201,17 +3063,13 @@
      * @param uid the uid of the app to update rules for
      * @param oldUidRules the current rules for the uid, in order to determine if there's a change
      * @param paroled whether to ignore idle state of apps and only look at other restrictions.
-     * @param notify whether to notify network policy listeners (INetworkPolicyListener) if the
-     *               rules are updated.
      *
-     * @return ReturnStatus includes new updated rules and whether network policy listeners
-     *         (INetworkPolicyListener) need to be notified.
+     * @return the new computed rules for the uid
      */
-    private ReturnStatus updateRulesForPowerRestrictionsUL(int uid, int oldUidRules,
-            boolean paroled, boolean notify) {
+    private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
         if (!isUidValidForBlacklistRules(uid)) {
             if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
-            return new ReturnStatus(false, RULE_NONE);
+            return RULE_NONE;
         }
 
         final boolean isIdle = !paroled && isUidIdle(uid);
@@ -3263,23 +3121,10 @@
                         + ", newRule=" + uidRulesToString(newUidRules)
                         + ", oldRule=" + uidRulesToString(oldUidRules));
             }
-            if (notify) {
-                mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
-            }
-            return new ReturnStatus(true, newUidRules);
+            mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
         }
 
-        return new ReturnStatus(false, newUidRules);
-    }
-
-    private static final class ReturnStatus {
-        boolean mNeedToNotify;
-        int mNewUidRules;
-
-        ReturnStatus(boolean needToNotify, int newUidRules) {
-            mNeedToNotify = needToNotify;
-            mNewUidRules = newUidRules;
-        }
+        return newUidRules;
     }
 
     private class AppIdleStateChangeListener
@@ -3293,7 +3138,7 @@
                 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
                 synchronized (mUidRulesFirstLock) {
                     updateRuleForAppIdleUL(uid);
-                    updateRulesForPowerRestrictionsUL(uid, true);
+                    updateRulesForPowerRestrictionsUL(uid);
                 }
             } catch (NameNotFoundException nnfe) {
             }
@@ -3353,26 +3198,13 @@
                 case MSG_RULES_CHANGED: {
                     final int uid = msg.arg1;
                     final int uidRules = msg.arg2;
-                    if (uidRules != RULE_INVALID) {
-                        dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
+                    dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
+                    final int length = mListeners.beginBroadcast();
+                    for (int i = 0; i < length; i++) {
+                        final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
+                        dispatchUidRulesChanged(listener, uid, uidRules);
                     }
-                    final Long procStateSeq = (Long) msg.obj;
-                    if (procStateSeq != null) {
-                        synchronized (mDispatchedThirdLock) {
-                            if (mLastHandledProcStateSeq.get(uid) == procStateSeq) {
-                                setDispatchedFlagDL(uid, procStateSeq, FLAG_UID_RULES_DISPATCHED);
-                                checkAndNotifyDL(uid, procStateSeq);
-                            }
-                        }
-                    }
-                    if (uidRules != RULE_INVALID) {
-                        final int length = mListeners.beginBroadcast();
-                        for (int i = 0; i < length; i++) {
-                            final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
-                            dispatchUidRulesChanged(listener, uid, uidRules);
-                        }
-                        mListeners.finishBroadcast();
-                    }
+                    mListeners.finishBroadcast();
                     return true;
                 }
                 case MSG_METERED_IFACES_CHANGED: {
diff --git a/services/core/java/com/android/server/notification/RankingHelper.java b/services/core/java/com/android/server/notification/RankingHelper.java
index 76890b1..867af9a 100644
--- a/services/core/java/com/android/server/notification/RankingHelper.java
+++ b/services/core/java/com/android/server/notification/RankingHelper.java
@@ -32,6 +32,7 @@
 import android.content.pm.ParceledListSlice;
 import android.os.Build;
 import android.os.UserHandle;
+import android.provider.Settings;
 import android.service.notification.NotificationListenerService.Ranking;
 import android.text.TextUtils;
 import android.util.ArrayMap;
@@ -516,6 +517,10 @@
         if (!r.showBadge) {
             channel.setShowBadge(false);
         }
+        if (channel.getSound() == null) {
+            channel.setSound(Settings.System.DEFAULT_NOTIFICATION_URI,
+                    Notification.AUDIO_ATTRIBUTES_DEFAULT);
+        }
         r.channels.put(channel.getId(), channel);
         updateConfig();
     }
diff --git a/services/core/java/com/android/server/pm/Installer.java b/services/core/java/com/android/server/pm/Installer.java
index db04515..5abdb60 100644
--- a/services/core/java/com/android/server/pm/Installer.java
+++ b/services/core/java/com/android/server/pm/Installer.java
@@ -63,6 +63,9 @@
     public static final int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
     public static final int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
     public static final int FLAG_USE_QUOTA = 1 << 12;
+    public static final int FLAG_FREE_CACHE_V2 = 1 << 13;
+    public static final int FLAG_FREE_CACHE_V2_DEFY_QUOTA = 1 << 14;
+    public static final int FLAG_FREE_CACHE_NOOP = 1 << 15;
 
     private final boolean mIsolated;
 
diff --git a/services/core/java/com/android/server/pm/LauncherAppsService.java b/services/core/java/com/android/server/pm/LauncherAppsService.java
index 96a2577..c11131a 100644
--- a/services/core/java/com/android/server/pm/LauncherAppsService.java
+++ b/services/core/java/com/android/server/pm/LauncherAppsService.java
@@ -242,6 +242,12 @@
             try {
                 UserInfo callingUserInfo = mUm.getUserInfo(callingUserId);
                 if (callingUserInfo.isManagedProfile()) {
+
+                    // STOPSHIP Remove the whitelist.
+                    if ("com.google.android.talk".equals(callingPackage)
+                            || "com.google.android.quicksearchbox".equals(callingPackage)) {
+                        return false;
+                    }
                     Slog.wtfStack(TAG, message + " by " + callingPackage + " for another profile "
                             + targetUserId + " from " + callingUserId);
 
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index dff78ba..fe2fb66 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -251,6 +251,7 @@
 import com.android.internal.os.Zygote;
 import com.android.internal.telephony.CarrierAppUtils;
 import com.android.internal.util.ArrayUtils;
+import com.android.internal.util.ConcurrentUtils;
 import com.android.internal.util.FastPrintWriter;
 import com.android.internal.util.FastXmlSerializer;
 import com.android.internal.util.IndentingPrintWriter;
@@ -265,6 +266,7 @@
 import com.android.server.LocalServices;
 import com.android.server.ServiceThread;
 import com.android.server.SystemConfig;
+import com.android.server.SystemServerInitThreadPool;
 import com.android.server.Watchdog;
 import com.android.server.net.NetworkPolicyManagerInternal;
 import com.android.server.pm.Installer.InstallerException;
@@ -322,6 +324,7 @@
 import java.util.Objects;
 import java.util.Set;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -392,8 +395,8 @@
     private static final boolean DISABLE_EPHEMERAL_APPS = false;
     private static final boolean HIDE_EPHEMERAL_APIS = false;
 
-    private static final boolean ENABLE_QUOTA =
-            SystemProperties.getBoolean("persist.fw.quota", false);
+    private static final boolean ENABLE_FREE_CACHE_V2 =
+            SystemProperties.getBoolean("fw.free_cache_v2", false);
 
     private static final int RADIO_UID = Process.PHONE_UID;
     private static final int LOG_UID = Process.LOG_UID;
@@ -857,6 +860,8 @@
 
     private ArraySet<String> mPrivappPermissionsViolations;
 
+    private Future<?> mPrepareAppDataFuture;
+
     private static class IFVerificationParams {
         PackageParser.Package pkg;
         boolean replacing;
@@ -2757,8 +2762,32 @@
             } else {
                 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
             }
-            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
-                    storageFlags, true /* migrateAppData */);
+            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
+                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
+                    true /* onlyCoreApps */);
+            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
+                if (deferPackages == null || deferPackages.isEmpty()) {
+                    return;
+                }
+                int count = 0;
+                for (String pkgName : deferPackages) {
+                    PackageParser.Package pkg = null;
+                    synchronized (mPackages) {
+                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
+                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
+                            pkg = ps.pkg;
+                        }
+                    }
+                    if (pkg != null) {
+                        synchronized (mInstallLock) {
+                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
+                                    true /* maybeMigrateAppData */);
+                        }
+                        count++;
+                    }
+                }
+                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
+            }, "prepareAppData");
 
             // If this is first boot after an OTA, and a normal boot, then
             // we need to clear code cache directories.
@@ -3765,25 +3794,19 @@
             final IPackageDataObserver observer) {
         mContext.enforceCallingOrSelfPermission(
                 android.Manifest.permission.CLEAR_APP_CACHE, null);
-        // Queue up an async operation since clearing cache may take a little while.
-        mHandler.post(new Runnable() {
-            public void run() {
-                mHandler.removeCallbacks(this);
-                boolean success = true;
-                synchronized (mInstallLock) {
-                    try {
-                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
-                    } catch (InstallerException e) {
-                        Slog.w(TAG, "Couldn't clear application caches: " + e);
-                        success = false;
-                    }
-                }
-                if (observer != null) {
-                    try {
-                        observer.onRemoveCompleted(null, success);
-                    } catch (RemoteException e) {
-                        Slog.w(TAG, "RemoveException when invoking call back");
-                    }
+        mHandler.post(() -> {
+            boolean success = false;
+            try {
+                freeStorage(volumeUuid, freeStorageSize, 0);
+                success = true;
+            } catch (IOException e) {
+                Slog.w(TAG, e);
+            }
+            if (observer != null) {
+                try {
+                    observer.onRemoveCompleted(null, success);
+                } catch (RemoteException e) {
+                    Slog.w(TAG, e);
                 }
             }
         });
@@ -3793,43 +3816,77 @@
     public void freeStorage(final String volumeUuid, final long freeStorageSize,
             final IntentSender pi) {
         mContext.enforceCallingOrSelfPermission(
-                android.Manifest.permission.CLEAR_APP_CACHE, null);
-        // Queue up an async operation since clearing cache may take a little while.
-        mHandler.post(new Runnable() {
-            public void run() {
-                mHandler.removeCallbacks(this);
-                boolean success = true;
-                synchronized (mInstallLock) {
-                    try {
-                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
-                    } catch (InstallerException e) {
-                        Slog.w(TAG, "Couldn't clear application caches: " + e);
-                        success = false;
-                    }
-                }
-                if(pi != null) {
-                    try {
-                        // Callback via pending intent
-                        int code = success ? 1 : 0;
-                        pi.sendIntent(null, code, null,
-                                null, null);
-                    } catch (SendIntentException e1) {
-                        Slog.i(TAG, "Failed to send pending intent");
-                    }
+                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
+        mHandler.post(() -> {
+            boolean success = false;
+            try {
+                freeStorage(volumeUuid, freeStorageSize, 0);
+                success = true;
+            } catch (IOException e) {
+                Slog.w(TAG, e);
+            }
+            if (pi != null) {
+                try {
+                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
+                } catch (SendIntentException e) {
+                    Slog.w(TAG, e);
                 }
             }
         });
     }
 
-    public void freeStorage(String volumeUuid, long freeStorageSize, int storageFlags)
-            throws IOException {
-        synchronized (mInstallLock) {
-            try {
-                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
-            } catch (InstallerException e) {
-                throw new IOException("Failed to free enough space", e);
+    /**
+     * Blocking call to clear various types of cached data across the system
+     * until the requested bytes are available.
+     */
+    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
+        final StorageManager storage = mContext.getSystemService(StorageManager.class);
+        final File file = storage.findPathForUuid(volumeUuid);
+
+        if (ENABLE_FREE_CACHE_V2) {
+            final boolean aggressive = (storageFlags
+                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
+
+            // 1. Pre-flight to determine if we have any chance to succeed
+            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
+
+            // 3. Consider parsed APK data (aggressive only)
+            if (aggressive) {
+                FileUtils.deleteContents(mCacheDir);
             }
+            if (file.getUsableSpace() >= bytes) return;
+
+            // 4. Consider cached app data (above quotas)
+            try {
+                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
+            } catch (InstallerException ignored) {
+            }
+            if (file.getUsableSpace() >= bytes) return;
+
+            // 5. Consider shared libraries with refcount=0 and age>2h
+            // 6. Consider dexopt output (aggressive only)
+            // 7. Consider ephemeral apps not used in last week
+
+            // 8. Consider cached app data (below quotas)
+            try {
+                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
+                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
+            } catch (InstallerException ignored) {
+            }
+            if (file.getUsableSpace() >= bytes) return;
+
+            // 9. Consider DropBox entries
+            // 10. Consider ephemeral cookies
+
+        } else {
+            try {
+                mInstaller.freeCache(volumeUuid, bytes, 0);
+            } catch (InstallerException ignored) {
+            }
+            if (file.getUsableSpace() >= bytes) return;
         }
+
+        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
     }
 
     /**
@@ -14205,88 +14262,6 @@
         abstract void handleReturnCode();
     }
 
-    class MeasureParams extends HandlerParams {
-        private final PackageStats mStats;
-        private boolean mSuccess;
-
-        private final IPackageStatsObserver mObserver;
-
-        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
-            super(new UserHandle(stats.userHandle));
-            mObserver = observer;
-            mStats = stats;
-        }
-
-        @Override
-        public String toString() {
-            return "MeasureParams{"
-                + Integer.toHexString(System.identityHashCode(this))
-                + " " + mStats.packageName + "}";
-        }
-
-        @Override
-        void handleStartCopy() throws RemoteException {
-            synchronized (mInstallLock) {
-                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
-            }
-
-            if (mSuccess) {
-                boolean mounted = false;
-                try {
-                    final String status = Environment.getExternalStorageState();
-                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
-                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
-                } catch (Exception e) {
-                }
-
-                if (mounted) {
-                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
-
-                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
-                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
-
-                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
-                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
-
-                    // Always subtract cache size, since it's a subdirectory
-                    mStats.externalDataSize -= mStats.externalCacheSize;
-
-                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
-                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
-
-                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
-                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
-                }
-            }
-        }
-
-        @Override
-        void handleReturnCode() {
-            if (mObserver != null) {
-                try {
-                    mObserver.onGetStatsCompleted(mStats, mSuccess);
-                } catch (RemoteException e) {
-                    Slog.i(TAG, "Observer no longer exists.");
-                }
-            }
-        }
-
-        @Override
-        void handleServiceError() {
-            Slog.e(TAG, "Could not measure application " + mStats.packageName
-                            + " external storage");
-        }
-    }
-
-    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
-            throws RemoteException {
-        long result = 0;
-        for (File path : paths) {
-            result += mcs.calculateDirectorySize(path.getAbsolutePath());
-        }
-        return result;
-    }
-
     private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
         for (File path : paths) {
             try {
@@ -18742,21 +18717,11 @@
     @Override
     public void getPackageSizeInfo(final String packageName, int userHandle,
             final IPackageStatsObserver observer) {
-        mContext.enforceCallingOrSelfPermission(
-                android.Manifest.permission.GET_PACKAGE_SIZE, null);
-        if (packageName == null) {
-            throw new IllegalArgumentException("Attempt to get size of null packageName");
+        Slog.w(TAG, "Shame on you for calling a hidden API. Shame!");
+        try {
+            observer.onGetStatsCompleted(null, false);
+        } catch (RemoteException ignored) {
         }
-
-        PackageStats stats = new PackageStats(packageName, userHandle);
-
-        /*
-         * Queue up an async operation since the package measurement may take a
-         * little while.
-         */
-        Message msg = mHandler.obtainMessage(INIT_COPY);
-        msg.obj = new MeasureParams(stats, observer);
-        mHandler.sendMessage(msg);
     }
 
     private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
@@ -20171,6 +20136,14 @@
         }
     }
 
+    public void waitForAppDataPrepared() {
+        if (mPrepareAppDataFuture == null) {
+            return;
+        }
+        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
+        mPrepareAppDataFuture = null;
+    }
+
     @Override
     public boolean isSafeMode() {
         return mSafeMode;
@@ -21621,6 +21594,11 @@
         }
     }
 
+    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
+            boolean migrateAppData) {
+        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
+    }
+
     /**
      * Reconcile all app data on given mounted volume.
      * <p>
@@ -21629,11 +21607,13 @@
      * <p>
      * Verifies that directories exist and that ownership and labeling is
      * correct for all installed apps.
+     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
      */
-    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
-            boolean migrateAppData) {
+    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
+            boolean migrateAppData, boolean onlyCoreApps) {
         Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
                 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
+        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
 
         final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
         final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
@@ -21697,21 +21677,20 @@
                 // and reconcile again once they're scanned
                 continue;
             }
+            // Skip non-core apps if requested
+            if (onlyCoreApps && !ps.pkg.coreApp) {
+                result.add(packageName);
+                continue;
+            }
 
             if (ps.getInstalled(userId)) {
-                prepareAppDataLIF(ps.pkg, userId, flags);
-
-                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
-                    // We may have just shuffled around app data directories, so
-                    // prepare them one more time
-                    prepareAppDataLIF(ps.pkg, userId, flags);
-                }
-
+                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
                 preparedCount++;
             }
         }
 
         Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
+        return result;
     }
 
     /**
@@ -21772,6 +21751,17 @@
         }
     }
 
+    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
+            boolean maybeMigrateAppData) {
+        prepareAppDataLIF(pkg, userId, flags);
+
+        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
+            // We may have just shuffled around app data directories, so
+            // prepare them one more time
+            prepareAppDataLIF(pkg, userId, flags);
+        }
+    }
+
     private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
         if (DEBUG_APP_DATA) {
             Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
diff --git a/services/core/java/com/android/server/vr/VrManagerService.java b/services/core/java/com/android/server/vr/VrManagerService.java
index 21a4f74..d179ea7 100644
--- a/services/core/java/com/android/server/vr/VrManagerService.java
+++ b/services/core/java/com/android/server/vr/VrManagerService.java
@@ -130,7 +130,7 @@
     private final ArrayDeque<VrState> mLoggingDeque = new ArrayDeque<>(EVENT_LOG_SIZE);
     private final NotificationAccessManager mNotifAccessManager = new NotificationAccessManager();
     /** Tracks the state of the screen and keyguard UI.*/
-    private int mSystemSleepFlags = FLAG_NONE;
+    private int mSystemSleepFlags = FLAG_AWAKE;
 
     private static final int MSG_VR_STATE_CHANGE = 0;
     private static final int MSG_PENDING_VR_STATE_CHANGE = 1;
diff --git a/services/core/java/com/android/server/wm/AccessibilityController.java b/services/core/java/com/android/server/wm/AccessibilityController.java
index f7a9e41..b7479da 100644
--- a/services/core/java/com/android/server/wm/AccessibilityController.java
+++ b/services/core/java/com/android/server/wm/AccessibilityController.java
@@ -226,8 +226,8 @@
             Matrix outMatrix) {
         sTempFloats[Matrix.MSCALE_X] = windowState.mWinAnimator.mDsDx;
         sTempFloats[Matrix.MSKEW_Y] = windowState.mWinAnimator.mDtDx;
-        sTempFloats[Matrix.MSKEW_X] = windowState.mWinAnimator.mDsDy;
-        sTempFloats[Matrix.MSCALE_Y] = windowState.mWinAnimator.mDtDy;
+        sTempFloats[Matrix.MSKEW_X] = windowState.mWinAnimator.mDtDy;
+        sTempFloats[Matrix.MSCALE_Y] = windowState.mWinAnimator.mDsDy;
         sTempFloats[Matrix.MTRANS_X] = windowState.mShownPosition.x;
         sTempFloats[Matrix.MTRANS_Y] = windowState.mShownPosition.y;
         sTempFloats[Matrix.MPERSP_0] = 0;
diff --git a/services/core/java/com/android/server/wm/BoundsAnimationController.java b/services/core/java/com/android/server/wm/BoundsAnimationController.java
index 01bd86d..837b69e 100644
--- a/services/core/java/com/android/server/wm/BoundsAnimationController.java
+++ b/services/core/java/com/android/server/wm/BoundsAnimationController.java
@@ -272,18 +272,10 @@
         void onAnimationEnd();
 
         void moveToFullscreen();
-
-        void getFullScreenBounds(Rect bounds);
     }
 
-    void animateBounds(final AnimateBoundsUser target, Rect from, Rect to, int animationDuration) {
-        boolean moveToFullscreen = false;
-        if (to == null) {
-            to = new Rect();
-            target.getFullScreenBounds(to);
-            moveToFullscreen = true;
-        }
-
+    void animateBounds(final AnimateBoundsUser target, Rect from, Rect to, int animationDuration,
+            boolean moveToFullscreen) {
         final BoundsAnimator existing = mRunningAnimations.get(target);
         final boolean replacing = existing != null;
 
diff --git a/services/core/java/com/android/server/wm/PinnedStackController.java b/services/core/java/com/android/server/wm/PinnedStackController.java
index cfeb198..5f41187 100644
--- a/services/core/java/com/android/server/wm/PinnedStackController.java
+++ b/services/core/java/com/android/server/wm/PinnedStackController.java
@@ -230,28 +230,6 @@
     }
 
     /**
-     * @return the movement bounds for the given {@param stackBounds} and the current state of the
-     *         controller.
-     */
-    private Rect getMovementBounds(Rect stackBounds) {
-        return getMovementBounds(stackBounds, true /* adjustForIme */);
-    }
-
-    /**
-     * @return the movement bounds for the given {@param stackBounds} and the current state of the
-     *         controller.
-     */
-    private Rect getMovementBounds(Rect stackBounds, boolean adjustForIme) {
-        final Rect movementBounds = new Rect();
-        getInsetBounds(movementBounds);
-
-        // Apply the movement bounds adjustments based on the current state
-        mSnapAlgorithm.getMovementBounds(stackBounds, movementBounds, movementBounds,
-                (adjustForIme && mIsImeShowing) ? mImeHeight : 0);
-        return movementBounds;
-    }
-
-    /**
      * @param preChangeTargetBounds The final bounds of the stack if it is currently animating
      * @return the repositioned PIP bounds given it's pre-change bounds, and the new display
      *         content.
@@ -387,6 +365,28 @@
     }
 
     /**
+     * @return the movement bounds for the given {@param stackBounds} and the current state of the
+     *         controller.
+     */
+    private Rect getMovementBounds(Rect stackBounds) {
+        return getMovementBounds(stackBounds, true /* adjustForIme */);
+    }
+
+    /**
+     * @return the movement bounds for the given {@param stackBounds} and the current state of the
+     *         controller.
+     */
+    private Rect getMovementBounds(Rect stackBounds, boolean adjustForIme) {
+        final Rect movementBounds = new Rect();
+        getInsetBounds(movementBounds);
+
+        // Apply the movement bounds adjustments based on the current state
+        mSnapAlgorithm.getMovementBounds(stackBounds, movementBounds, movementBounds,
+                (adjustForIme && mIsImeShowing) ? mImeHeight : 0);
+        return movementBounds;
+    }
+
+    /**
      * Applies the minimized offsets to the given stack bounds.
      */
     private void applyMinimizedOffset(Rect stackBounds, Rect movementBounds) {
diff --git a/services/core/java/com/android/server/wm/PinnedStackWindowController.java b/services/core/java/com/android/server/wm/PinnedStackWindowController.java
new file mode 100644
index 0000000..71f88de
--- /dev/null
+++ b/services/core/java/com/android/server/wm/PinnedStackWindowController.java
@@ -0,0 +1,122 @@
+/*
+ * 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.server.wm;
+
+import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID;
+
+import android.app.RemoteAction;
+import android.graphics.Rect;
+
+import com.android.server.UiThread;
+
+import java.util.List;
+
+/**
+ * Controller for the pinned stack container. See {@link StackWindowController}.
+ */
+public class PinnedStackWindowController extends StackWindowController {
+
+    private Rect mTmpBoundsRect = new Rect();
+
+    public PinnedStackWindowController(int stackId, StackWindowListener listener, int displayId,
+            boolean onTop, Rect outBounds) {
+        super(stackId, listener, displayId, onTop, outBounds, WindowManagerService.getInstance());
+    }
+
+    /**
+     * Animates the pinned stack.
+     */
+    public void animateResizePinnedStack(Rect bounds, int animationDuration) {
+        synchronized (mWindowMap) {
+            if (mContainer == null) {
+                throw new IllegalArgumentException("Pinned stack container not found :(");
+            }
+
+            // Get non-null fullscreen bounds if the bounds are null
+            final boolean moveToFullscreen = bounds == null;
+            bounds = getPinnedStackAnimationBounds(bounds);
+
+            // If the bounds are truly null, then there was no fullscreen stack at this time, so
+            // animate this to the full display bounds
+            final Rect toBounds;
+            if (bounds == null) {
+                toBounds = new Rect();
+                mContainer.getDisplayContent().getLogicalDisplayRect(toBounds);
+            } else {
+                toBounds = bounds;
+            }
+
+            final Rect originalBounds = new Rect();
+            mContainer.getBounds(originalBounds);
+            mContainer.setAnimatingBounds(toBounds);
+            UiThread.getHandler().post(() -> {
+                mService.mBoundsAnimationController.animateBounds(mContainer, originalBounds,
+                        toBounds, animationDuration, moveToFullscreen);
+            });
+        }
+    }
+
+    /**
+     * Sets the current picture-in-picture aspect ratio.
+     */
+    public void setPictureInPictureAspectRatio(float aspectRatio) {
+        synchronized (mWindowMap) {
+            if (!mService.mSupportsPictureInPicture || mContainer == null) {
+                return;
+            }
+
+            final int displayId = mContainer.getDisplayContent().getDisplayId();
+            final Rect toBounds = mService.getPictureInPictureBounds(displayId, aspectRatio);
+            final Rect targetBounds = new Rect();
+            mContainer.getAnimatingBounds(targetBounds);
+            if (!toBounds.equals(targetBounds)) {
+                animateResizePinnedStack(toBounds, -1 /* duration */);
+            }
+
+            final PinnedStackController pinnedStackController =
+                    mContainer.getDisplayContent().getPinnedStackController();
+            pinnedStackController.setAspectRatio(
+                    pinnedStackController.isValidPictureInPictureAspectRatio(aspectRatio)
+                            ? aspectRatio : -1f);
+        }
+    }
+
+    /**
+     * Sets the current picture-in-picture actions.
+     */
+    public void setPictureInPictureActions(List<RemoteAction> actions) {
+        synchronized (mWindowMap) {
+            if (!mService.mSupportsPictureInPicture || mContainer == null) {
+                return;
+            }
+
+            mContainer.getDisplayContent().getPinnedStackController().setActions(actions);
+        }
+    }
+
+    /**
+     * Checks the {@param bounds} and retirms non-null fullscreen bounds for the pinned stack
+     * animation if necessary.
+     */
+    private Rect getPinnedStackAnimationBounds(Rect bounds) {
+        mService.getStackBounds(FULLSCREEN_WORKSPACE_STACK_ID, mTmpBoundsRect);
+        if (bounds == null && !mTmpBoundsRect.isEmpty()) {
+            bounds = new Rect(mTmpBoundsRect);
+        }
+        return bounds;
+    }
+}
diff --git a/services/core/java/com/android/server/wm/StackWindowController.java b/services/core/java/com/android/server/wm/StackWindowController.java
index 142f69a..b0e115b 100644
--- a/services/core/java/com/android/server/wm/StackWindowController.java
+++ b/services/core/java/com/android/server/wm/StackWindowController.java
@@ -199,59 +199,6 @@
         }
     }
 
-    // TODO: This and similar methods should be separated into PinnedStackWindowContainerController
-    public void animateResizePinnedStack(final Rect bounds, final int animationDuration) {
-        synchronized (mWindowMap) {
-            if (mContainer == null) {
-                throw new IllegalArgumentException("Pinned stack container not found :(");
-            }
-            final Rect originalBounds = new Rect();
-            mContainer.getBounds(originalBounds);
-            mContainer.setAnimatingBounds(bounds);
-            UiThread.getHandler().post(new Runnable() {
-                @Override
-                public void run() {
-                    mService.mBoundsAnimationController.animateBounds(
-                            mContainer, originalBounds, bounds, animationDuration);
-                }
-            });
-        }
-    }
-
-    /** Sets the current picture-in-picture aspect ratio. */
-    public void setPictureInPictureAspectRatio(float aspectRatio) {
-        synchronized (mWindowMap) {
-            if (!mService.mSupportsPictureInPicture || mContainer == null) {
-                return;
-            }
-
-            final int displayId = mContainer.getDisplayContent().getDisplayId();
-            final Rect toBounds = mService.getPictureInPictureBounds(displayId, aspectRatio);
-            final Rect targetBounds = new Rect();
-            mContainer.getAnimatingBounds(targetBounds);
-            if (!toBounds.equals(targetBounds)) {
-                animateResizePinnedStack(toBounds, -1 /* duration */);
-            }
-
-            final PinnedStackController pinnedStackController =
-                    mContainer.getDisplayContent().getPinnedStackController();
-            pinnedStackController.setAspectRatio(
-                    pinnedStackController.isValidPictureInPictureAspectRatio(aspectRatio)
-                            ? aspectRatio : -1f);
-        }
-    }
-
-    /** Sets the current picture-in-picture actions. */
-    public void setPictureInPictureActions(List<RemoteAction> actions) {
-        synchronized (mWindowMap) {
-            if (!mService.mSupportsPictureInPicture || mContainer == null) {
-                return;
-            }
-
-            mContainer.getDisplayContent().getPinnedStackController().setActions(actions);
-        }
-    }
-
     public void getStackDockedModeBounds(Rect outBounds, Rect outTempBounds,
             Rect outTempInsetBounds, boolean ignoreVisibility) {
         synchronized (mWindowMap) {
diff --git a/services/core/java/com/android/server/wm/TaskStack.java b/services/core/java/com/android/server/wm/TaskStack.java
index 5f8b694..c7532ac 100644
--- a/services/core/java/com/android/server/wm/TaskStack.java
+++ b/services/core/java/com/android/server/wm/TaskStack.java
@@ -19,6 +19,7 @@
 import static android.app.ActivityManager.DOCKED_STACK_CREATE_MODE_TOP_OR_LEFT;
 import static android.app.ActivityManager.DOCKED_STACK_CREATE_MODE_BOTTOM_OR_RIGHT;
 import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
+import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID;
 import static android.app.ActivityManager.StackId.HOME_STACK_ID;
 import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSET;
@@ -1476,14 +1477,6 @@
         }
     }
 
-    @Override
-    public void getFullScreenBounds(Rect bounds) {
-        // This is currently only used for the pinned stack animation when leaving PiP
-        // (see {@link BoundsAnimationController}), and in that case we need to animate this back
-        // to the full bounds to match the fullscreen stack
-        getDisplayContent().getLogicalDisplayRect(bounds);
-    }
-
     public boolean hasMovementAnimations() {
         return StackId.hasMovementAnimations(mStackId);
     }
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 9397c9e..474610b 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -7267,10 +7267,6 @@
         return mRoot.getDisplayContentOrCreate(DEFAULT_DISPLAY);
     }
 
-    private DisplayInfo getDefaultDisplayInfoLocked() {
-        return getDefaultDisplayContentLocked().getDisplayInfo();
-    }
-
     public void onDisplayAdded(int displayId) {
         mH.sendMessage(mH.obtainMessage(H.DO_DISPLAY_ADDED, displayId, 0));
     }
diff --git a/services/core/java/com/android/server/wm/WindowStateAnimator.java b/services/core/java/com/android/server/wm/WindowStateAnimator.java
index c0929cb..98598e1 100644
--- a/services/core/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowStateAnimator.java
@@ -172,7 +172,7 @@
     private boolean mAnimateMove = false;
 
     float mDsDx=1, mDtDx=0, mDsDy=0, mDtDy=1;
-    float mLastDsDx=1, mLastDtDx=0, mLastDsDy=0, mLastDtDy=1;
+    private float mLastDsDx=1, mLastDtDx=0, mLastDsDy=0, mLastDtDy=1;
 
     boolean mHaveMatrix;
 
@@ -945,8 +945,8 @@
             tmpMatrix.getValues(tmpFloats);
             mDsDx = tmpFloats[Matrix.MSCALE_X];
             mDtDx = tmpFloats[Matrix.MSKEW_Y];
-            mDsDy = tmpFloats[Matrix.MSKEW_X];
-            mDtDy = tmpFloats[Matrix.MSCALE_Y];
+            mDtDy = tmpFloats[Matrix.MSKEW_X];
+            mDsDy = tmpFloats[Matrix.MSCALE_Y];
             float x = tmpFloats[Matrix.MTRANS_X];
             float y = tmpFloats[Matrix.MTRANS_Y];
             mWin.mShownPosition.set(Math.round(x), Math.round(y));
@@ -959,7 +959,7 @@
             mShownAlpha = mAlpha;
             if (!mService.mLimitedAlphaCompositing
                     || (!PixelFormat.formatHasAlpha(mWin.mAttrs.format)
-                    || (mWin.isIdentityMatrix(mDsDx, mDtDx, mDsDy, mDtDy)
+                    || (mWin.isIdentityMatrix(mDsDx, mDtDx, mDtDy, mDsDy)
                             && x == frame.left && y == frame.top))) {
                 //Slog.i(TAG_WM, "Applying alpha transform");
                 if (selfTransformation) {
@@ -1038,8 +1038,8 @@
             mHaveMatrix = true;
             mDsDx = tmpFloats[Matrix.MSCALE_X];
             mDtDx = tmpFloats[Matrix.MSKEW_Y];
-            mDsDy = tmpFloats[Matrix.MSKEW_X];
-            mDtDy = tmpFloats[Matrix.MSCALE_Y];
+            mDtDy = tmpFloats[Matrix.MSKEW_X];
+            mDsDy = tmpFloats[Matrix.MSCALE_Y];
             float x = tmpFloats[Matrix.MTRANS_X];
             float y = tmpFloats[Matrix.MTRANS_Y];
             mWin.mShownPosition.set(Math.round(x), Math.round(y));
@@ -1054,8 +1054,8 @@
             mHaveMatrix = false;
             mDsDx = mWin.mGlobalScale;
             mDtDx = 0;
-            mDsDy = 0;
-            mDtDy = mWin.mGlobalScale;
+            mDtDy = 0;
+            mDsDy = mWin.mGlobalScale;
         }
     }
 
@@ -1384,8 +1384,8 @@
             applyCrop(clipRect, finalClipRect, recoveringMemory);
             mSurfaceController.setMatrixInTransaction(mDsDx * w.mHScale * mExtraHScale,
                     mDtDx * w.mVScale * mExtraVScale,
-                    mDsDy * w.mHScale * mExtraHScale,
-                    mDtDy * w.mVScale * mExtraVScale, recoveringMemory);
+                    mDtDy * w.mHScale * mExtraHScale,
+                    mDsDy * w.mVScale * mExtraVScale, recoveringMemory);
         }
 
         if (mSurfaceResized) {
@@ -1467,15 +1467,15 @@
                     "alpha=" + mShownAlpha + " layer=" + mAnimLayer
                     + " matrix=[" + mDsDx + "*" + w.mHScale
                     + "," + mDtDx + "*" + w.mVScale
-                    + "][" + mDsDy + "*" + w.mHScale
-                    + "," + mDtDy + "*" + w.mVScale + "]", false);
+                    + "][" + mDtDy + "*" + w.mHScale
+                    + "," + mDsDy + "*" + w.mVScale + "]", false);
 
             boolean prepared =
                 mSurfaceController.prepareToShowInTransaction(mShownAlpha, mAnimLayer,
                         mDsDx * w.mHScale * mExtraHScale,
                         mDtDx * w.mVScale * mExtraVScale,
-                        mDsDy * w.mHScale * mExtraHScale,
-                        mDtDy * w.mVScale * mExtraVScale,
+                        mDtDy * w.mHScale * mExtraHScale,
+                        mDsDy * w.mVScale * mExtraVScale,
                         recoveringMemory);
 
             if (prepared && mLastHidden && mDrawState == HAS_DRAWN) {
@@ -1777,8 +1777,8 @@
             pw.print(prefix); pw.print("mGlobalScale="); pw.print(mWin.mGlobalScale);
                     pw.print(" mDsDx="); pw.print(mDsDx);
                     pw.print(" mDtDx="); pw.print(mDtDx);
-                    pw.print(" mDsDy="); pw.print(mDsDy);
-                    pw.print(" mDtDy="); pw.println(mDtDy);
+                    pw.print(" mDtDy="); pw.print(mDtDy);
+                    pw.print(" mDsDy="); pw.println(mDsDy);
         }
         if (mAnimationStartDelayed) {
             pw.print(prefix); pw.print("mAnimationStartDelayed="); pw.print(mAnimationStartDelayed);
@@ -1926,15 +1926,15 @@
 
             float DsDx = mService.mTmpFloats[Matrix.MSCALE_X];
             float DtDx = mService.mTmpFloats[Matrix.MSKEW_Y];
-            float DsDy = mService.mTmpFloats[Matrix.MSKEW_X];
-            float DtDy = mService.mTmpFloats[Matrix.MSCALE_Y];
+            float DtDy = mService.mTmpFloats[Matrix.MSKEW_X];
+            float DsDy = mService.mTmpFloats[Matrix.MSCALE_Y];
             float nx = mService.mTmpFloats[Matrix.MTRANS_X];
             float ny = mService.mTmpFloats[Matrix.MTRANS_Y];
             mSurfaceController.setPositionInTransaction(nx, ny, false);
             mSurfaceController.setMatrixInTransaction(DsDx * w.mHScale,
                     DtDx * w.mVScale,
-                    DsDy * w.mHScale,
-                    DtDy * w.mVScale, false);
+                    DtDy * w.mHScale,
+                    DsDy * w.mVScale, false);
         }
     }
 
diff --git a/services/core/jni/com_android_server_location_ContextHubService.cpp b/services/core/jni/com_android_server_location_ContextHubService.cpp
index 05ef0d1..27d2b6d 100644
--- a/services/core/jni/com_android_server_location_ContextHubService.cpp
+++ b/services/core/jni/com_android_server_location_ContextHubService.cpp
@@ -558,7 +558,7 @@
 void initContextHubService() {
     db.hubInfo.numHubs = 0;
 
-    db.hubInfo.contextHub = IContexthub::getService("context_hub");
+    db.hubInfo.contextHub = IContexthub::getService();
 
     if (db.hubInfo.contextHub == nullptr) {
         ALOGE("Could not load context hub hal");
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index c8a80c2..a5f1945 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -182,10 +182,8 @@
             "com.google.android.clockwork.ThermalObserver";
     private static final String WEAR_BLUETOOTH_SERVICE_CLASS =
             "com.google.android.clockwork.bluetooth.WearBluetoothService";
-    private static final String WEAR_WIFI_MEDIATOR_SERVICE_CLASS =
-            "com.google.android.clockwork.wifi.WearWifiMediatorService";
-    private static final String WEAR_CELLULAR_MEDIATOR_SERVICE_CLASS =
-            "com.google.android.clockwork.cellular.WearCellularMediatorService";
+    private static final String WEAR_CONNECTIVITY_SERVICE_CLASS =
+            "com.google.android.clockwork.connectivity.WearConnectivityService";
     private static final String WEAR_TIME_SERVICE_CLASS =
             "com.google.android.clockwork.time.WearTimeService";
     private static final String ACCOUNT_SERVICE_CLASS =
@@ -376,6 +374,7 @@
             startBootstrapServices();
             startCoreServices();
             startOtherServices();
+            SystemServerInitThreadPool.shutdown();
         } catch (Throwable ex) {
             Slog.e("System", "******************************************");
             Slog.e("System", "************ Failure starting system services", ex);
@@ -383,7 +382,6 @@
         } finally {
             traceEnd();
         }
-        SystemServerInitThreadPool.shutdown();
 
         // For debug builds, log event loop stalls to dropbox for analysis.
         if (StrictMode.conditionallyEnableDebugLogging()) {
@@ -1459,16 +1457,10 @@
             mSystemServiceManager.startService(WEAR_BLUETOOTH_SERVICE_CLASS);
             traceEnd();
 
-            traceBeginAndSlog("StartWearWifiMediator");
-            mSystemServiceManager.startService(WEAR_WIFI_MEDIATOR_SERVICE_CLASS);
+            traceBeginAndSlog("StartWearConnectivityService");
+            mSystemServiceManager.startService(WEAR_CONNECTIVITY_SERVICE_CLASS);
             traceEnd();
 
-            if (SystemProperties.getBoolean("config.enable_cellmediator", false)) {
-                traceBeginAndSlog("StartWearCellularMediator");
-                mSystemServiceManager.startService(WEAR_CELLULAR_MEDIATOR_SERVICE_CLASS);
-                traceEnd();
-            }
-
             if (!disableNonCoreServices) {
                 traceBeginAndSlog("StartWearTimeService");
                 mSystemServiceManager.startService(WEAR_TIME_SERVICE_CLASS);
@@ -1694,6 +1686,9 @@
             Watchdog.getInstance().start();
             traceEnd();
 
+            // Wait for all packages to be prepared
+            mPackageManagerService.waitForAppDataPrepared();
+
             // It is now okay to let the various system services start their
             // third party code...
             traceBeginAndSlog("PhaseThirdPartyAppsCanStart");
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 9ea9ce9..8210072 100644
--- a/services/tests/notification/src/com/android/server/notification/RankingHelperTest.java
+++ b/services/tests/notification/src/com/android/server/notification/RankingHelperTest.java
@@ -776,6 +776,26 @@
     }
 
     @Test
+    public void testCreateChannel_addMissingSound() throws Exception {
+        final NotificationChannel channel =
+                new NotificationChannel("id2", "name2", IMPORTANCE_LOW);
+        mHelper.createNotificationChannel(pkg, uid, channel, true);
+        assertNotNull(mHelper.getNotificationChannel(
+                pkg, uid, channel.getId(), false).getSound());
+    }
+
+    @Test
+    public void testCreateChannel_noOverrideSound() throws Exception {
+        Uri sound = new Uri.Builder().scheme("test").build();
+        final NotificationChannel channel = new NotificationChannel("id2", "name2",
+                 NotificationManager.IMPORTANCE_DEFAULT);
+        channel.setSound(sound, mAudioAttributes);
+        mHelper.createNotificationChannel(pkg, uid, channel, true);
+        assertEquals(sound, mHelper.getNotificationChannel(
+                pkg, uid, channel.getId(), false).getSound());
+    }
+
+    @Test
     public void testPermanentlyDeleteChannels() throws Exception {
         NotificationChannel channel1 =
                 new NotificationChannel("id1", "name1", NotificationManager.IMPORTANCE_HIGH);
diff --git a/services/tests/servicestests/src/com/android/server/NetworkScoreServiceTest.java b/services/tests/servicestests/src/com/android/server/NetworkScoreServiceTest.java
index c0b79be..665f01f 100644
--- a/services/tests/servicestests/src/com/android/server/NetworkScoreServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/NetworkScoreServiceTest.java
@@ -120,14 +120,16 @@
     private static final String INVALID_BSSID = "invalid_bssid";
     private static final ComponentName RECOMMENDATION_SERVICE_COMP =
             new ComponentName("newPackageName", "newScoringServiceClass");
+    private static final ComponentName USE_WIFI_ENABLE_ACTIVITY_COMP =
+            new ComponentName("useWifiPackageName", "enableUseWifiActivityClass");
     private static final ScoredNetwork SCORED_NETWORK =
             new ScoredNetwork(new NetworkKey(new WifiKey(quote(SSID), "00:00:00:00:00:00")),
                     null /* rssiCurve*/);
     private static final ScoredNetwork SCORED_NETWORK_2 =
             new ScoredNetwork(new NetworkKey(new WifiKey(quote(SSID_2), "00:00:00:00:00:00")),
                     null /* rssiCurve*/);
-    private static final NetworkScorerAppData NEW_SCORER =
-        new NetworkScorerAppData(1, RECOMMENDATION_SERVICE_COMP);
+    private static final NetworkScorerAppData NEW_SCORER = new NetworkScorerAppData(
+            1, RECOMMENDATION_SERVICE_COMP, USE_WIFI_ENABLE_ACTIVITY_COMP);
 
     @Mock private NetworkScorerAppManager mNetworkScorerAppManager;
     @Mock private Context mContext;
@@ -661,6 +663,8 @@
 
         assertEquals(NEW_SCORER.getRecommendationServicePackageName(),
                 mNetworkScoreService.getActiveScorerPackage());
+        assertEquals(NEW_SCORER.getEnableUseOpenWifiActivity(),
+                mNetworkScoreService.getActiveScorer().getEnableUseOpenWifiActivity());
     }
 
     @Test
@@ -920,8 +924,8 @@
             throws Exception {
         when(mContext.checkCallingOrSelfPermission(permission.REQUEST_NETWORK_SCORES))
                 .thenReturn(PackageManager.PERMISSION_GRANTED);
-        NetworkScorerAppData expectedAppData =
-                new NetworkScorerAppData(Binder.getCallingUid(), RECOMMENDATION_SERVICE_COMP);
+        NetworkScorerAppData expectedAppData = new NetworkScorerAppData(Binder.getCallingUid(),
+                RECOMMENDATION_SERVICE_COMP, USE_WIFI_ENABLE_ACTIVITY_COMP);
         bindToScorer(expectedAppData);
         assertEquals(expectedAppData, mNetworkScoreService.getActiveScorer());
     }
@@ -961,8 +965,8 @@
 
     private void bindToScorer(boolean callerIsScorer) {
         final int callingUid = callerIsScorer ? Binder.getCallingUid() : Binder.getCallingUid() + 1;
-        NetworkScorerAppData appData =
-                new NetworkScorerAppData(callingUid, RECOMMENDATION_SERVICE_COMP);
+        NetworkScorerAppData appData = new NetworkScorerAppData(callingUid,
+                RECOMMENDATION_SERVICE_COMP, USE_WIFI_ENABLE_ACTIVITY_COMP);
         bindToScorer(appData);
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/usage/StorageStatsServiceTest.java b/services/tests/servicestests/src/com/android/server/usage/StorageStatsServiceTest.java
new file mode 100644
index 0000000..baee865
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/usage/StorageStatsServiceTest.java
@@ -0,0 +1,55 @@
+/*
+ * 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.server.usage;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.provider.Settings;
+import android.test.AndroidTestCase;
+import android.test.mock.MockContentResolver;
+
+import com.android.internal.util.test.FakeSettingsProvider;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class StorageStatsServiceTest extends AndroidTestCase {
+    private MockContentResolver mContentResolver;
+
+    @Before
+    public void setUp() throws Exception {
+        super.setUp();
+        mContentResolver = new MockContentResolver();
+        mContentResolver.addProvider(Settings.AUTHORITY, new FakeSettingsProvider());
+    }
+
+    @Test
+    public void testDontRunWhenDisabledFromSettingsGlobal() throws Exception {
+        Settings.Global.putInt(mContentResolver, Settings.Global.ENABLE_CACHE_QUOTA_CALCULATION, 0);
+
+        assertThat(StorageStatsService.isCacheQuotaCalculationsEnabled(mContentResolver)).isFalse();
+    }
+
+    @Test
+    public void testCalculationTaskIsEnabledByDefault() throws Exception {
+        // Put null to act as though there is no value here.
+        Settings.Global.putString(
+                mContentResolver, Settings.Global.ENABLE_CACHE_QUOTA_CALCULATION, null);
+
+        assertThat(StorageStatsService.isCacheQuotaCalculationsEnabled(mContentResolver)).isTrue();
+    }
+}
diff --git a/services/usage/java/com/android/server/usage/StorageStatsService.java b/services/usage/java/com/android/server/usage/StorageStatsService.java
index a44860e..ed1530a 100644
--- a/services/usage/java/com/android/server/usage/StorageStatsService.java
+++ b/services/usage/java/com/android/server/usage/StorageStatsService.java
@@ -21,6 +21,7 @@
 import android.app.usage.IStorageStatsManager;
 import android.app.usage.StorageStats;
 import android.app.usage.UsageStatsManagerInternal;
+import android.content.ContentResolver;
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
@@ -29,6 +30,7 @@
 import android.content.pm.UserInfo;
 import android.os.Binder;
 import android.os.Environment;
+import android.os.FileUtils;
 import android.os.Handler;
 import android.os.Looper;
 import android.os.Message;
@@ -39,9 +41,11 @@
 import android.os.storage.StorageEventListener;
 import android.os.storage.StorageManager;
 import android.os.storage.VolumeInfo;
+import android.provider.Settings;
 import android.text.format.DateUtils;
 import android.util.Slog;
 
+import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.ArrayUtils;
 import com.android.internal.util.Preconditions;
 import com.android.server.IoThread;
@@ -145,11 +149,10 @@
         enforcePermission(Binder.getCallingUid(), callingPackage);
 
         if (volumeUuid == StorageManager.UUID_PRIVATE_INTERNAL) {
-            // TODO: round total size to nearest power of two
-            return mStorage.getPrimaryStorageSize();
+            return FileUtils.roundStorageSize(mStorage.getPrimaryStorageSize());
         } else {
             final VolumeInfo vol = mStorage.findVolumeByUuid(volumeUuid);
-            return vol.disk.size;
+            return FileUtils.roundStorageSize(vol.disk.size);
         }
     }
 
@@ -172,6 +175,43 @@
     }
 
     @Override
+    public StorageStats queryStatsForPackage(String volumeUuid, String packageName, int userId,
+            String callingPackage) {
+        enforcePermission(Binder.getCallingUid(), callingPackage);
+        if (userId != UserHandle.getCallingUserId()) {
+            mContext.enforceCallingOrSelfPermission(
+                    android.Manifest.permission.INTERACT_ACROSS_USERS, TAG);
+        }
+
+        final ApplicationInfo appInfo;
+        try {
+            appInfo = mPackage.getApplicationInfoAsUser(packageName, 0, userId);
+        } catch (NameNotFoundException e) {
+            throw new IllegalStateException(e);
+        }
+
+        if (mPackage.getPackagesForUid(appInfo.uid).length == 1) {
+            // Only one package inside UID means we can fast-path
+            return queryStatsForUid(volumeUuid, appInfo.uid, callingPackage);
+        } else {
+            // Multiple packages means we need to go manual
+            final int appId = UserHandle.getUserId(appInfo.uid);
+            final String[] packageNames = new String[] { packageName };
+            final long[] ceDataInodes = new long[1];
+            final String[] codePaths = new String[] { appInfo.getCodePath() };
+
+            final PackageStats stats = new PackageStats(TAG);
+            try {
+                mInstaller.getAppSize(volumeUuid, packageNames, userId, 0,
+                        appId, ceDataInodes, codePaths, stats);
+            } catch (InstallerException e) {
+                throw new IllegalStateException(e);
+            }
+            return translate(stats);
+        }
+    }
+
+    @Override
     public StorageStats queryStatsForUid(String volumeUuid, int uid, String callingPackage) {
         enforcePermission(Binder.getCallingUid(), callingPackage);
         if (UserHandle.getUserId(uid) != UserHandle.getCallingUserId()) {
@@ -328,6 +368,11 @@
             if (DEBUG) {
                 Slog.v(TAG, ">>> handling " + msg.what);
             }
+
+            if (!isCacheQuotaCalculationsEnabled(mContext.getContentResolver())) {
+                return;
+            }
+
             switch (msg.what) {
                 case MSG_CHECK_STORAGE_DELTA: {
                     long bytesDelta = Math.abs(mPreviousBytes - mStats.getFreeBytes());
@@ -359,4 +404,10 @@
             strategy.recalculateQuotas();
         }
     }
+
+    @VisibleForTesting
+    static boolean isCacheQuotaCalculationsEnabled(ContentResolver resolver) {
+        return Settings.Global.getInt(
+                resolver, Settings.Global.ENABLE_CACHE_QUOTA_CALCULATION, 1) != 0;
+    }
 }
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index 7c9c0e8..a4235d7 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -6144,7 +6144,7 @@
      * android.content.pm.PackageManager#FEATURE_TELEPHONY_CARRIERLOCK} enabled.
      *
      * @return The number of carriers set successfully. Should be length of
-     * carrierList on success; -1 on error.
+     * carrierList on success; -1 if carrierList null or on error.
      * @hide
      */
     @SystemApi
diff --git a/telephony/java/android/telephony/ims/stub/ImsCallSessionImplBase.java b/telephony/java/android/telephony/ims/stub/ImsCallSessionImplBase.java
new file mode 100644
index 0000000..69b8acc
--- /dev/null
+++ b/telephony/java/android/telephony/ims/stub/ImsCallSessionImplBase.java
@@ -0,0 +1,348 @@
+/*
+ * 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.telephony.ims.stub;
+
+import android.os.Message;
+import android.os.RemoteException;
+
+import com.android.ims.ImsCallProfile;
+import com.android.ims.ImsStreamMediaProfile;
+import com.android.ims.internal.ImsCallSession;
+import com.android.ims.internal.IImsCallSession;
+import com.android.ims.internal.IImsCallSessionListener;
+import com.android.ims.internal.IImsVideoCallProvider;
+
+/**
+ * Base implementation of IImsCallSession, which implements stub versions of the methods in the
+ * IImsCallSession AIDL. Override the methods that your implementation of ImsCallSession supports.
+ *
+ * DO NOT remove or change the existing APIs, only add new ones to this Base implementation or you
+ * will break other implementations of ImsCallSession maintained by other ImsServices.
+ *
+ * @hide
+ */
+
+public class ImsCallSessionImplBase extends IImsCallSession.Stub {
+
+    /**
+     * Closes the object. This object is not usable after being closed.
+     */
+    @Override
+    public void close() throws RemoteException {
+
+    }
+
+    /**
+     * Gets the call ID of the session.
+     *
+     * @return the call ID
+     */
+    @Override
+    public String getCallId() throws RemoteException {
+        return null;
+    }
+
+    /**
+     * Gets the call profile that this session is associated with
+     *
+     * @return the {@link ImsCallProfile} that this session is associated with
+     */
+    @Override
+    public ImsCallProfile getCallProfile() throws RemoteException {
+        return null;
+    }
+
+    /**
+     * Gets the local call profile that this session is associated with
+     *
+     * @return the local {@link ImsCallProfile} that this session is associated with
+     */
+    @Override
+    public ImsCallProfile getLocalCallProfile() throws RemoteException {
+        return null;
+    }
+
+    /**
+     * Gets the remote call profile that this session is associated with
+     *
+     * @return the remote {@link ImsCallProfile} that this session is associated with
+     */
+    @Override
+    public ImsCallProfile getRemoteCallProfile() throws RemoteException {
+        return null;
+    }
+
+    /**
+     * Gets the value associated with the specified property of this session.
+     *
+     * @return the string value associated with the specified property
+     */
+    @Override
+    public String getProperty(String name) throws RemoteException {
+        return null;
+    }
+
+    /**
+     * Gets the session state.
+     * The value returned must be one of the states in {@link ImsCallSession.State}.
+     *
+     * @return the session state
+     */
+    @Override
+    public int getState() throws RemoteException {
+        return ImsCallSession.State.INVALID;
+    }
+
+    /**
+     * Checks if the session is in call.
+     *
+     * @return true if the session is in call, false otherwise
+     */
+    @Override
+    public boolean isInCall() throws RemoteException {
+        return false;
+    }
+
+    /**
+     * Sets the listener to listen to the session events. An {@link ImsCallSession}
+     * can only hold one listener at a time. Subsequent calls to this method
+     * override the previous listener.
+     *
+     * @param listener to listen to the session events of this object
+     */
+    @Override
+    public void setListener(IImsCallSessionListener listener) throws RemoteException {
+    }
+
+    /**
+     * Mutes or unmutes the mic for the active call.
+     *
+     * @param muted true if the call is muted, false otherwise
+     */
+    @Override
+    public void setMute(boolean muted) throws RemoteException {
+    }
+
+    /**
+     * Initiates an IMS call with the specified target and call profile.
+     * The session listener set in {@link #setListener} is called back upon defined session events.
+     * The method is only valid to call when the session state is in
+     * {@link ImsCallSession.State#IDLE}.
+     *
+     * @param callee dialed string to make the call to
+     * @param profile call profile to make the call with the specified service type,
+     *      call type and media information
+     * @see {@link ImsCallSession.Listener#callSessionStarted},
+     * {@link ImsCallSession.Listener#callSessionStartFailed}
+     */
+    @Override
+    public void start(String callee, ImsCallProfile profile) throws RemoteException {
+    }
+
+    /**
+     * Initiates an IMS call with the specified participants and call profile.
+     * The session listener set in {@link #setListener} is called back upon defined session events.
+     * The method is only valid to call when the session state is in
+     * {@link ImsCallSession.State#IDLE}.
+     *
+     * @param participants participant list to initiate an IMS conference call
+     * @param profile call profile to make the call with the specified service type,
+     *      call type and media information
+     * @see {@link ImsCallSession.Listener#callSessionStarted},
+     * {@link ImsCallSession.Listener#callSessionStartFailed}
+     */
+    @Override
+    public void startConference(String[] participants, ImsCallProfile profile)
+            throws RemoteException {
+    }
+
+    /**
+     * Accepts an incoming call or session update.
+     *
+     * @param callType call type specified in {@link ImsCallProfile} to be answered
+     * @param profile stream media profile {@link ImsStreamMediaProfile} to be answered
+     * @see {@link ImsCallSession.Listener#callSessionStarted}
+     */
+    @Override
+    public void accept(int callType, ImsStreamMediaProfile profile) throws RemoteException {
+    }
+
+    /**
+     * Rejects an incoming call or session update.
+     *
+     * @param reason reason code to reject an incoming call, defined in
+     *         com.android.ims.ImsReasonInfo
+     * {@link ImsCallSession.Listener#callSessionStartFailed}
+     */
+    @Override
+    public void reject(int reason) throws RemoteException {
+    }
+
+    /**
+     * Terminates a call.
+     *
+     * @param reason reason code to terminate a call, defined in
+     *         com.android.ims.ImsReasonInfo
+     *
+     * @see {@link ImsCallSession.Listener#callSessionTerminated}
+     */
+    @Override
+    public void terminate(int reason) throws RemoteException {
+    }
+
+    /**
+     * Puts a call on hold. When it succeeds, {@link ImsCallSession.Listener#callSessionHeld} is
+     * called.
+     *
+     * @param profile stream media profile {@link ImsStreamMediaProfile} to hold the call
+     * @see {@link ImsCallSession.Listener#callSessionHeld},
+     * {@link ImsCallSession.Listener#callSessionHoldFailed}
+     */
+    @Override
+    public void hold(ImsStreamMediaProfile profile) throws RemoteException {
+    }
+
+    /**
+     * Continues a call that's on hold. When it succeeds,
+     * {@link ImsCallSession.Listener#callSessionResumed} is called.
+     *
+     * @param profile stream media profile with {@link ImsStreamMediaProfile} to resume the call
+     * @see {@link ImsCallSession.Listener#callSessionResumed},
+     * {@link ImsCallSession.Listener#callSessionResumeFailed}
+     */
+    @Override
+    public void resume(ImsStreamMediaProfile profile) throws RemoteException {
+    }
+
+    /**
+     * Merges the active & hold call. When the merge starts,
+     * {@link ImsCallSession.Listener#callSessionMergeStarted} is called.
+     * {@link ImsCallSession.Listener#callSessionMergeComplete} is called if the merge is
+     * successful, and {@link ImsCallSession.Listener#callSessionMergeFailed} is called if the merge
+     * fails.
+     *
+     * @see {@link ImsCallSession.Listener#callSessionMergeStarted},
+     * {@link ImsCallSession.Listener#callSessionMergeComplete},
+     *      {@link ImsCallSession.Listener#callSessionMergeFailed}
+     */
+    @Override
+    public void merge() throws RemoteException {
+    }
+
+    /**
+     * Updates the current call's properties (ex. call mode change: video upgrade / downgrade).
+     *
+     * @param callType call type specified in {@link ImsCallProfile} to be updated
+     * @param profile stream media profile {@link ImsStreamMediaProfile} to be updated
+     * @see {@link ImsCallSession.Listener#callSessionUpdated},
+     * {@link ImsCallSession.Listener#callSessionUpdateFailed}
+     */
+    @Override
+    public void update(int callType, ImsStreamMediaProfile profile) throws RemoteException {
+    }
+
+    /**
+     * Extends this call to the conference call with the specified recipients.
+     *
+     * @param participants participant list to be invited to the conference call after extending the
+     * call
+     * @see {@link ImsCallSession.Listener#callSessionConferenceExtended},
+     * {@link ImsCallSession.Listener#callSessionConferenceExtendFailed}
+     */
+    @Override
+    public void extendToConference(String[] participants) throws RemoteException {
+    }
+
+    /**
+     * Requests the conference server to invite an additional participants to the conference.
+     *
+     * @param participants participant list to be invited to the conference call
+     * @see {@link ImsCallSession.Listener#callSessionInviteParticipantsRequestDelivered},
+     *      {@link ImsCallSession.Listener#callSessionInviteParticipantsRequestFailed}
+     */
+    @Override
+    public void inviteParticipants(String[] participants) throws RemoteException {
+    }
+
+    /**
+     * Requests the conference server to remove the specified participants from the conference.
+     *
+     * @param participants participant list to be removed from the conference call
+     * @see {@link ImsCallSession.Listener#callSessionRemoveParticipantsRequestDelivered},
+     *      {@link ImsCallSession.Listener#callSessionRemoveParticipantsRequestFailed}
+     */
+    @Override
+    public void removeParticipants(String[] participants) throws RemoteException {
+    }
+
+    /**
+     * Sends a DTMF code. According to <a href="http://tools.ietf.org/html/rfc2833">RFC 2833</a>,
+     * event 0 ~ 9 maps to decimal value 0 ~ 9, '*' to 10, '#' to 11, event 'A' ~ 'D' to 12 ~ 15,
+     * and event flash to 16. Currently, event flash is not supported.
+     *
+     * @param c the DTMF to send. '0' ~ '9', 'A' ~ 'D', '*', '#' are valid inputs.
+     */
+    @Override
+    public void sendDtmf(char c, Message result) throws RemoteException {
+    }
+
+    /**
+     * Start a DTMF code. According to <a href="http://tools.ietf.org/html/rfc2833">RFC 2833</a>,
+     * event 0 ~ 9 maps to decimal value 0 ~ 9, '*' to 10, '#' to 11, event 'A' ~ 'D' to 12 ~ 15,
+     * and event flash to 16. Currently, event flash is not supported.
+     *
+     * @param c the DTMF to send. '0' ~ '9', 'A' ~ 'D', '*', '#' are valid inputs.
+     */
+    @Override
+    public void startDtmf(char c) throws RemoteException {
+    }
+
+    /**
+     * Stop a DTMF code.
+     */
+    @Override
+    public void stopDtmf() throws RemoteException {
+    }
+
+    /**
+     * Sends an USSD message.
+     *
+     * @param ussdMessage USSD message to send
+     */
+    @Override
+    public void sendUssd(String ussdMessage) throws RemoteException {
+    }
+
+    /**
+     * Returns a binder for the video call provider implementation contained within the IMS service
+     * process. This binder is used by the VideoCallProvider subclass in Telephony which
+     * intermediates between the propriety implementation and Telecomm/InCall.
+     */
+    @Override
+    public IImsVideoCallProvider getVideoCallProvider() throws RemoteException {
+        return null;
+    }
+
+    /**
+     * Determines if the current session is multiparty.
+     * @return {@code True} if the session is multiparty.
+     */
+    @Override
+    public boolean isMultiparty() throws RemoteException {
+        return false;
+    }
+}
diff --git a/telephony/java/android/telephony/ims/stub/ImsCallSessionListenerImplBase.java b/telephony/java/android/telephony/ims/stub/ImsCallSessionListenerImplBase.java
new file mode 100644
index 0000000..46f8f80
--- /dev/null
+++ b/telephony/java/android/telephony/ims/stub/ImsCallSessionListenerImplBase.java
@@ -0,0 +1,251 @@
+/*
+ * 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.telephony.ims.stub;
+
+import com.android.ims.ImsCallProfile;
+import com.android.ims.ImsConferenceState;
+import com.android.ims.ImsReasonInfo;
+import com.android.ims.ImsStreamMediaProfile;
+import com.android.ims.ImsSuppServiceNotification;
+import com.android.ims.internal.IImsCallSession;
+import com.android.ims.internal.IImsCallSessionListener;
+
+/**
+ * Base implementation of ImsCallSessionListenerBase, which implements stub versions of the methods
+ * in the IImsCallSessionListener AIDL. Override the methods that your implementation of
+ * ImsCallSessionListener supports.
+ *
+ * DO NOT remove or change the existing APIs, only add new ones to this Base implementation or you
+ * will break other implementations of ImsCallSessionListener maintained by other ImsServices.
+ *
+ * @hide
+ */
+public class ImsCallSessionListenerImplBase extends IImsCallSessionListener.Stub {
+    /**
+     * Notifies the result of the basic session operation (setup / terminate).
+     */
+    @Override
+    public void callSessionProgressing(IImsCallSession session, ImsStreamMediaProfile profile) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionStarted(IImsCallSession session, ImsCallProfile profile) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionStartFailed(IImsCallSession session, ImsReasonInfo reasonInfo) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionTerminated(IImsCallSession session, ImsReasonInfo reasonInfo) {
+        // no-op
+    }
+
+    /**
+     * Notifies the result of the call hold/resume operation.
+     */
+    @Override
+    public void callSessionHeld(IImsCallSession session, ImsCallProfile profile) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionHoldFailed(IImsCallSession session, ImsReasonInfo reasonInfo) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionHoldReceived(IImsCallSession session, ImsCallProfile profile) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionResumed(IImsCallSession session, ImsCallProfile profile) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionResumeFailed(IImsCallSession session, ImsReasonInfo reasonInfo) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionResumeReceived(IImsCallSession session, ImsCallProfile profile) {
+        // no-op
+    }
+
+    /**
+     * Notifies the result of call merge operation.
+     */
+    @Override
+    public void callSessionMergeStarted(IImsCallSession session, IImsCallSession newSession,
+            ImsCallProfile profile) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionMergeComplete(IImsCallSession session) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionMergeFailed(IImsCallSession session, ImsReasonInfo reasonInfo) {
+        // no-op
+    }
+
+    /**
+     * Notifies the result of call upgrade / downgrade or any other call
+     * updates.
+     */
+    @Override
+    public void callSessionUpdated(IImsCallSession session, ImsCallProfile profile) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionUpdateFailed(IImsCallSession session, ImsReasonInfo reasonInfo) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionUpdateReceived(IImsCallSession session, ImsCallProfile profile) {
+        // no-op
+    }
+
+    /**
+     * Notifies the result of conference extension.
+     */
+    @Override
+    public void callSessionConferenceExtended(IImsCallSession session, IImsCallSession newSession,
+            ImsCallProfile profile) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionConferenceExtendFailed(IImsCallSession session,
+            ImsReasonInfo reasonInfo) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionConferenceExtendReceived(IImsCallSession session,
+            IImsCallSession newSession,
+            ImsCallProfile profile) {
+        // no-op
+    }
+
+    /**
+     * Notifies the result of the participant invitation / removal to/from the
+     * conference session.
+     */
+    @Override
+    public void callSessionInviteParticipantsRequestDelivered(IImsCallSession session) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionInviteParticipantsRequestFailed(IImsCallSession session,
+            ImsReasonInfo reasonInfo) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionRemoveParticipantsRequestDelivered(IImsCallSession session) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionRemoveParticipantsRequestFailed(IImsCallSession session,
+            ImsReasonInfo reasonInfo) {
+        // no-op
+    }
+
+    /**
+     * Notifies the changes of the conference info. the conference session.
+     */
+    @Override
+    public void callSessionConferenceStateUpdated(IImsCallSession session,
+            ImsConferenceState state) {
+        // no-op
+    }
+
+    /**
+     * Notifies the incoming USSD message.
+     */
+    @Override
+    public void callSessionUssdMessageReceived(IImsCallSession session, int mode,
+            String ussdMessage) {
+        // no-op
+    }
+
+    /**
+     * Notifies of handover information for this call
+     */
+    @Override
+    public void callSessionHandover(IImsCallSession session, int srcAccessTech,
+            int targetAccessTech,
+            ImsReasonInfo reasonInfo) {
+        // no-op
+    }
+
+    @Override
+    public void callSessionHandoverFailed(IImsCallSession session, int srcAccessTech,
+            int targetAccessTech,
+            ImsReasonInfo reasonInfo) {
+        // no-op
+    }
+
+    /**
+     * Notifies the TTY mode change by remote party.
+     *
+     * @param mode one of the following: -
+     *            {@link com.android.internal.telephony.Phone#TTY_MODE_OFF} -
+     *            {@link com.android.internal.telephony.Phone#TTY_MODE_FULL} -
+     *            {@link com.android.internal.telephony.Phone#TTY_MODE_HCO} -
+     *            {@link com.android.internal.telephony.Phone#TTY_MODE_VCO}
+     */
+    @Override
+    public void callSessionTtyModeReceived(IImsCallSession session, int mode) {
+        // no-op
+    }
+
+    /**
+     * Notifies of a change to the multiparty state for this
+     * {@code ImsCallSession}.
+     *
+     * @param session The call session.
+     * @param isMultiParty {@code true} if the session became multiparty,
+     *            {@code false} otherwise.
+     */
+    @Override
+    public void callSessionMultipartyStateChanged(IImsCallSession session, boolean isMultiParty) {
+        // no-op
+    }
+
+    /**
+     * Notifies the supplementary service information for the current session.
+     */
+    @Override
+    public void callSessionSuppServiceReceived(IImsCallSession session,
+            ImsSuppServiceNotification suppSrvNotification) {
+        // no-op
+    }
+}
+
diff --git a/telephony/java/android/telephony/ims/stub/ImsConfigImplBase.java b/telephony/java/android/telephony/ims/stub/ImsConfigImplBase.java
new file mode 100644
index 0000000..5a4db99
--- /dev/null
+++ b/telephony/java/android/telephony/ims/stub/ImsConfigImplBase.java
@@ -0,0 +1,150 @@
+/*
+ * 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.telephony.ims.stub;
+
+import android.os.RemoteException;
+
+import com.android.ims.ImsConfig;
+import com.android.ims.ImsConfigListener;
+import com.android.ims.internal.IImsConfig;
+
+/**
+ * Base implementation of ImsConfig, which implements stub versions of the methods
+ * in the IImsConfig AIDL. Override the methods that your implementation of ImsConfig supports.
+ *
+ * DO NOT remove or change the existing APIs, only add new ones to this Base implementation or you
+ * will break other implementations of ImsConfig maintained by other ImsServices.
+ *
+ * Provides APIs to get/set the IMS service feature/capability/parameters.
+ * The config items include:
+ * 1) Items provisioned by the operator.
+ * 2) Items configured by user. Mainly service feature class.
+ *
+ * @hide
+ */
+
+public class ImsConfigImplBase extends IImsConfig.Stub {
+
+    /**
+     * Gets the value for ims service/capabilities parameters from the provisioned
+     * value storage. Synchronous blocking call.
+     *
+     * @param item, as defined in com.android.ims.ImsConfig#ConfigConstants.
+     * @return value in Integer format.
+     */
+    @Override
+    public int getProvisionedValue(int item) throws RemoteException {
+        return -1;
+    }
+
+    /**
+     * Gets the value for ims service/capabilities parameters from the provisioned
+     * value storage. Synchronous blocking call.
+     *
+     * @param item, as defined in com.android.ims.ImsConfig#ConfigConstants.
+     * @return value in String format.
+     */
+    @Override
+    public String getProvisionedStringValue(int item) throws RemoteException {
+        return null;
+    }
+
+    /**
+     * Sets the value for IMS service/capabilities parameters by the operator device
+     * management entity. It sets the config item value in the provisioned storage
+     * from which the master value is derived. Synchronous blocking call.
+     *
+     * @param item, as defined in com.android.ims.ImsConfig#ConfigConstants.
+     * @param value in Integer format.
+     * @return as defined in com.android.ims.ImsConfig#OperationStatusConstants.
+     */
+    @Override
+    public int setProvisionedValue(int item, int value) throws RemoteException {
+        return ImsConfig.OperationStatusConstants.FAILED;
+    }
+
+    /**
+     * Sets the value for IMS service/capabilities parameters by the operator device
+     * management entity. It sets the config item value in the provisioned storage
+     * from which the master value is derived.  Synchronous blocking call.
+     *
+     * @param item as defined in com.android.ims.ImsConfig#ConfigConstants.
+     * @param value in String format.
+     * @return as defined in com.android.ims.ImsConfig#OperationStatusConstants.
+     */
+    @Override
+    public int setProvisionedStringValue(int item, String value) throws RemoteException {
+        return ImsConfig.OperationStatusConstants.FAILED;
+    }
+
+    /**
+     * Gets the value of the specified IMS feature item for specified network type.
+     * This operation gets the feature config value from the master storage (i.e. final
+     * value). Asynchronous non-blocking call.
+     *
+     * @param feature as defined in com.android.ims.ImsConfig#FeatureConstants.
+     * @param network as defined in android.telephony.TelephonyManager#NETWORK_TYPE_XXX.
+     * @param listener feature value returned asynchronously through listener.
+     */
+    @Override
+    public void getFeatureValue(int feature, int network, ImsConfigListener listener)
+            throws RemoteException {
+    }
+
+    /**
+     * Sets the value for IMS feature item for specified network type.
+     * This operation stores the user setting in setting db from which master db
+     * is derived.
+     *
+     * @param feature as defined in com.android.ims.ImsConfig#FeatureConstants.
+     * @param network as defined in android.telephony.TelephonyManager#NETWORK_TYPE_XXX.
+     * @param value as defined in com.android.ims.ImsConfig#FeatureValueConstants.
+     * @param listener, provided if caller needs to be notified for set result.
+     */
+    @Override
+    public void setFeatureValue(int feature, int network, int value, ImsConfigListener listener)
+            throws RemoteException {
+    }
+
+    /**
+     * Gets the value for IMS VoLTE provisioned.
+     * This should be the same as the operator provisioned value if applies.
+     */
+    @Override
+    public boolean getVolteProvisioned() throws RemoteException {
+        return false;
+    }
+
+    /**
+     * Gets the value for IMS feature item video quality.
+     *
+     * @param listener Video quality value returned asynchronously through listener.
+     */
+    @Override
+    public void getVideoQuality(ImsConfigListener listener) throws RemoteException {
+    }
+
+    /**
+     * Sets the value for IMS feature item video quality.
+     *
+     * @param quality, defines the value of video quality.
+     * @param listener, provided if caller needs to be notified for set result.
+     */
+    @Override
+    public void setVideoQuality(int quality, ImsConfigListener listener) throws RemoteException {
+    }
+}
diff --git a/telephony/java/android/telephony/ims/stub/ImsEcbmImplBase.java b/telephony/java/android/telephony/ims/stub/ImsEcbmImplBase.java
new file mode 100644
index 0000000..89f95ff
--- /dev/null
+++ b/telephony/java/android/telephony/ims/stub/ImsEcbmImplBase.java
@@ -0,0 +1,51 @@
+/*
+ * 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.telephony.ims.stub;
+
+import android.os.RemoteException;
+
+import com.android.ims.internal.IImsEcbm;
+import com.android.ims.internal.IImsEcbmListener;
+
+/**
+ * Base implementation of ImsEcbm, which implements stub versions of the methods
+ * in the IImsEcbm AIDL. Override the methods that your implementation of ImsEcbm supports.
+ *
+ * DO NOT remove or change the existing APIs, only add new ones to this Base implementation or you
+ * will break other implementations of ImsEcbm maintained by other ImsServices.
+ *
+ * @hide
+ */
+
+public class ImsEcbmImplBase extends IImsEcbm.Stub {
+
+    /**
+     * Sets the listener.
+     */
+    @Override
+    public void setListener(IImsEcbmListener listener) throws RemoteException {
+
+    }
+
+    /**
+     * Requests Modem to come out of ECBM mode
+     */
+    @Override
+    public void exitEmergencyCallbackMode() throws RemoteException {
+
+    }
+}
diff --git a/telephony/java/android/telephony/ims/stub/ImsMultiEndpointImplBase.java b/telephony/java/android/telephony/ims/stub/ImsMultiEndpointImplBase.java
new file mode 100644
index 0000000..05da9da
--- /dev/null
+++ b/telephony/java/android/telephony/ims/stub/ImsMultiEndpointImplBase.java
@@ -0,0 +1,53 @@
+/*
+ * 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.telephony.ims.stub;
+
+import android.os.RemoteException;
+
+import com.android.ims.internal.IImsExternalCallStateListener;
+import com.android.ims.internal.IImsMultiEndpoint;
+
+/**
+ * Base implementation of ImsMultiEndpoint, which implements stub versions of the methods
+ * in the IImsMultiEndpoint AIDL. Override the methods that your implementation of
+ * ImsMultiEndpoint supports.
+ *
+ * DO NOT remove or change the existing APIs, only add new ones to this Base implementation or you
+ * will break other implementations of ImsMultiEndpoint maintained by other ImsServices.
+ *
+ * @hide
+ */
+
+public class ImsMultiEndpointImplBase extends IImsMultiEndpoint.Stub {
+
+    /**
+     * Sets the listener.
+     */
+    @Override
+    public void setListener(IImsExternalCallStateListener listener) throws RemoteException {
+
+    }
+
+    /**
+     * Query API to get the latest Dialog Event Package information
+     * Should be invoked only after setListener is done
+     */
+    @Override
+    public void requestImsExternalCallStateInfo() throws RemoteException {
+
+    }
+}
diff --git a/telephony/java/android/telephony/ims/stub/ImsStreamMediaSessionImplBase.java b/telephony/java/android/telephony/ims/stub/ImsStreamMediaSessionImplBase.java
new file mode 100644
index 0000000..92f1a01
--- /dev/null
+++ b/telephony/java/android/telephony/ims/stub/ImsStreamMediaSessionImplBase.java
@@ -0,0 +1,40 @@
+/*
+ * 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.telephony.ims.stub;
+
+import android.os.RemoteException;
+
+import com.android.ims.internal.IImsStreamMediaSession;
+
+/**
+ * Base implementation of ImsStreamMediaSession, which implements stub versions of the methods
+ * in the IImsStreamMediaSession AIDL. Override the methods that your implementation of
+ * ImsStreamMediaSession supports.
+ *
+ * DO NOT remove or change the existing APIs, only add new ones to this Base implementation or you
+ * will break other implementations of ImsStreamMediaSession maintained by other ImsServices.
+ *
+ * @hide
+ */
+
+public class ImsStreamMediaSessionImplBase extends IImsStreamMediaSession.Stub {
+
+    @Override
+    public void close() throws RemoteException {
+
+    }
+}
diff --git a/telephony/java/android/telephony/ims/stub/ImsUtImplBase.java b/telephony/java/android/telephony/ims/stub/ImsUtImplBase.java
new file mode 100644
index 0000000..dc74094
--- /dev/null
+++ b/telephony/java/android/telephony/ims/stub/ImsUtImplBase.java
@@ -0,0 +1,174 @@
+/*
+ * 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.telephony.ims.stub;
+
+import android.os.Bundle;
+import android.os.RemoteException;
+
+import com.android.ims.internal.IImsUt;
+import com.android.ims.internal.IImsUtListener;
+
+/**
+ * Base implementation of ImsUt, which implements stub versions of the methods
+ * in the IImsUt AIDL. Override the methods that your implementation of ImsUt supports.
+ *
+ * DO NOT remove or change the existing APIs, only add new ones to this Base implementation or you
+ * will break other implementations of ImsUt maintained by other ImsServices.
+ *
+ * Provides the Ut interface interworking to get/set the supplementary service configuration.
+ *
+ * @hide
+ */
+
+public class ImsUtImplBase extends IImsUt.Stub {
+
+    /**
+     * Closes the object. This object is not usable after being closed.
+     */
+    @Override
+    public void close() throws RemoteException {
+
+    }
+
+    /**
+     * Retrieves the configuration of the call barring.
+     */
+    @Override
+    public int queryCallBarring(int cbType) throws RemoteException {
+        return -1;
+    }
+
+    /**
+     * Retrieves the configuration of the call forward.
+     */
+    @Override
+    public int queryCallForward(int condition, String number) throws RemoteException {
+        return -1;
+    }
+
+    /**
+     * Retrieves the configuration of the call waiting.
+     */
+    @Override
+    public int queryCallWaiting() throws RemoteException {
+        return -1;
+    }
+
+    /**
+     * Retrieves the default CLIR setting.
+     */
+    @Override
+    public int queryCLIR() throws RemoteException {
+        return -1;
+    }
+
+    /**
+     * Retrieves the CLIP call setting.
+     */
+    @Override
+    public int queryCLIP() throws RemoteException {
+        return -1;
+    }
+
+    /**
+     * Retrieves the COLR call setting.
+     */
+    @Override
+    public int queryCOLR() throws RemoteException {
+        return -1;
+    }
+
+    /**
+     * Retrieves the COLP call setting.
+     */
+    @Override
+    public int queryCOLP() throws RemoteException {
+        return -1;
+    }
+
+    /**
+     * Updates or retrieves the supplementary service configuration.
+     */
+    @Override
+    public int transact(Bundle ssInfo) throws RemoteException {
+        return -1;
+    }
+
+    /**
+     * Updates the configuration of the call barring.
+     */
+    @Override
+    public int updateCallBarring(int cbType, int action, String[] barrList) throws RemoteException {
+        return -1;
+    }
+
+    /**
+     * Updates the configuration of the call forward.
+     */
+    @Override
+    public int updateCallForward(int action, int condition, String number, int serviceClass,
+            int timeSeconds) throws RemoteException {
+        return 0;
+    }
+
+    /**
+     * Updates the configuration of the call waiting.
+     */
+    @Override
+    public int updateCallWaiting(boolean enable, int serviceClass) throws RemoteException {
+        return -1;
+    }
+
+    /**
+     * Updates the configuration of the CLIR supplementary service.
+     */
+    @Override
+    public int updateCLIR(int clirMode) throws RemoteException {
+        return -1;
+    }
+
+    /**
+     * Updates the configuration of the CLIP supplementary service.
+     */
+    @Override
+    public int updateCLIP(boolean enable) throws RemoteException {
+        return -1;
+    }
+
+    /**
+     * Updates the configuration of the COLR supplementary service.
+     */
+    @Override
+    public int updateCOLR(int presentation) throws RemoteException {
+        return -1;
+    }
+
+    /**
+     * Updates the configuration of the COLP supplementary service.
+     */
+    @Override
+    public int updateCOLP(boolean enable) throws RemoteException {
+        return -1;
+    }
+
+    /**
+     * Sets the listener.
+     */
+    @Override
+    public void setListener(IImsUtListener listener) throws RemoteException {
+    }
+}
diff --git a/telephony/java/android/telephony/ims/stub/ImsUtListenerImplBase.java b/telephony/java/android/telephony/ims/stub/ImsUtListenerImplBase.java
new file mode 100644
index 0000000..b371efb
--- /dev/null
+++ b/telephony/java/android/telephony/ims/stub/ImsUtListenerImplBase.java
@@ -0,0 +1,88 @@
+/*
+ * 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.telephony.ims.stub;
+
+import android.os.Bundle;
+import android.os.RemoteException;
+
+import com.android.ims.ImsCallForwardInfo;
+import com.android.ims.ImsReasonInfo;
+import com.android.ims.ImsSsInfo;
+import com.android.ims.internal.IImsUt;
+import com.android.ims.internal.IImsUtListener;
+
+/**
+ * Base implementation of ImsUtListener, which implements stub versions of the methods
+ * in the IImsUtListener AIDL. Override the methods that your implementation of
+ * ImsUtListener supports.
+ *
+ * DO NOT remove or change the existing APIs, only add new ones to this Base implementation or you
+ * will break other implementations of ImsUtListener maintained by other ImsServices.
+ *
+ * @hide
+ */
+
+public class ImsUtListenerImplBase extends IImsUtListener.Stub {
+
+    /**
+     * Notifies the result of the supplementary service configuration udpate.
+     */
+    @Override
+    public void utConfigurationUpdated(IImsUt ut, int id) throws RemoteException {
+    }
+
+    @Override
+    public void utConfigurationUpdateFailed(IImsUt ut, int id, ImsReasonInfo error)
+            throws RemoteException {
+    }
+
+    /**
+     * Notifies the result of the supplementary service configuration query.
+     */
+    @Override
+    public void utConfigurationQueried(IImsUt ut, int id, Bundle ssInfo) throws RemoteException {
+    }
+
+    @Override
+    public void utConfigurationQueryFailed(IImsUt ut, int id, ImsReasonInfo error)
+            throws RemoteException {
+    }
+
+    /**
+     * Notifies the status of the call barring supplementary service.
+     */
+    @Override
+    public void utConfigurationCallBarringQueried(IImsUt ut, int id, ImsSsInfo[] cbInfo)
+            throws RemoteException {
+    }
+
+    /**
+     * Notifies the status of the call forwarding supplementary service.
+     */
+    @Override
+    public void utConfigurationCallForwardQueried(IImsUt ut, int id, ImsCallForwardInfo[] cfInfo)
+            throws RemoteException {
+    }
+
+    /**
+     * Notifies the status of the call waiting supplementary service.
+     */
+    @Override
+    public void utConfigurationCallWaitingQueried(IImsUt ut, int id, ImsSsInfo[] cwInfo)
+            throws RemoteException {
+    }
+}
diff --git a/telephony/java/com/android/ims/ImsConfig.java b/telephony/java/com/android/ims/ImsConfig.java
new file mode 100644
index 0000000..cd076b1
--- /dev/null
+++ b/telephony/java/com/android/ims/ImsConfig.java
@@ -0,0 +1,694 @@
+/*
+ * 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.ims;
+
+import android.content.Context;
+import android.os.RemoteException;
+import android.telephony.Rlog;
+
+import com.android.ims.internal.IImsConfig;
+
+/**
+ * Provides APIs to get/set the IMS service feature/capability/parameters.
+ * The config items include:
+ * 1) Items provisioned by the operator.
+ * 2) Items configured by user. Mainly service feature class.
+ *
+ * @hide
+ */
+public class ImsConfig {
+    private static final String TAG = "ImsConfig";
+    private boolean DBG = true;
+    private final IImsConfig miConfig;
+    private Context mContext;
+
+    /**
+     * Broadcast action: the feature enable status was changed
+     *
+     * @hide
+     */
+    public static final String ACTION_IMS_FEATURE_CHANGED =
+            "com.android.intent.action.IMS_FEATURE_CHANGED";
+
+    /**
+     * Broadcast action: the configuration was changed
+     *
+     * @hide
+     */
+    public static final String ACTION_IMS_CONFIG_CHANGED =
+            "com.android.intent.action.IMS_CONFIG_CHANGED";
+
+    /**
+     * Extra parameter "item" of intent ACTION_IMS_FEATURE_CHANGED and ACTION_IMS_CONFIG_CHANGED.
+     * It is the value of FeatureConstants or ConfigConstants.
+     *
+     * @hide
+     */
+    public static final String EXTRA_CHANGED_ITEM = "item";
+
+    /**
+     * Extra parameter "value" of intent ACTION_IMS_FEATURE_CHANGED and ACTION_IMS_CONFIG_CHANGED.
+     * It is the new value of "item".
+     *
+     * @hide
+     */
+    public static final String EXTRA_NEW_VALUE = "value";
+
+    /**
+    * Defines IMS service/capability feature constants.
+    */
+    public static class FeatureConstants {
+        public static final int FEATURE_TYPE_UNKNOWN = -1;
+
+        /**
+         * FEATURE_TYPE_VOLTE supports features defined in 3GPP and
+         * GSMA IR.92 over LTE.
+         */
+        public static final int FEATURE_TYPE_VOICE_OVER_LTE = 0;
+
+        /**
+         * FEATURE_TYPE_LVC supports features defined in 3GPP and
+         * GSMA IR.94 over LTE.
+         */
+        public static final int FEATURE_TYPE_VIDEO_OVER_LTE = 1;
+
+        /**
+         * FEATURE_TYPE_VOICE_OVER_WIFI supports features defined in 3GPP and
+         * GSMA IR.92 over WiFi.
+         */
+        public static final int FEATURE_TYPE_VOICE_OVER_WIFI = 2;
+
+        /**
+         * FEATURE_TYPE_VIDEO_OVER_WIFI supports features defined in 3GPP and
+         * GSMA IR.94 over WiFi.
+         */
+        public static final int FEATURE_TYPE_VIDEO_OVER_WIFI = 3;
+
+        /**
+         * FEATURE_TYPE_UT supports features defined in 3GPP and
+         * GSMA IR.92 over LTE.
+         */
+        public static final int FEATURE_TYPE_UT_OVER_LTE = 4;
+
+       /**
+         * FEATURE_TYPE_UT_OVER_WIFI supports features defined in 3GPP and
+         * GSMA IR.92 over WiFi.
+         */
+        public static final int FEATURE_TYPE_UT_OVER_WIFI = 5;
+    }
+
+    /**
+    * Defines IMS service/capability parameters.
+    */
+    public static class ConfigConstants {
+
+        // Define IMS config items
+        public static final int CONFIG_START = 0;
+
+        // Define operator provisioned config items
+        public static final int PROVISIONED_CONFIG_START = CONFIG_START;
+
+        /**
+         * AMR CODEC Mode Value set, 0-7 in comma separated sequence.
+         * Value is in String format.
+         */
+        public static final int VOCODER_AMRMODESET = CONFIG_START;
+
+        /**
+         * Wide Band AMR CODEC Mode Value set,0-7 in comma separated sequence.
+         * Value is in String format.
+         */
+        public static final int VOCODER_AMRWBMODESET = 1;
+
+        /**
+         * SIP Session Timer value (seconds).
+         * Value is in Integer format.
+         */
+        public static final int SIP_SESSION_TIMER = 2;
+
+        /**
+         * Minimum SIP Session Expiration Timer in (seconds).
+         * Value is in Integer format.
+         */
+        public static final int MIN_SE = 3;
+
+        /**
+         * SIP_INVITE cancellation time out value (in milliseconds). Integer format.
+         * Value is in Integer format.
+         */
+        public static final int CANCELLATION_TIMER = 4;
+
+        /**
+         * Delay time when an iRAT transition from eHRPD/HRPD/1xRTT to LTE.
+         * Value is in Integer format.
+         */
+        public static final int TDELAY = 5;
+
+        /**
+         * Silent redial status of Enabled (True), or Disabled (False).
+         * Value is in Integer format.
+         */
+        public static final int SILENT_REDIAL_ENABLE = 6;
+
+        /**
+         * SIP T1 timer value in milliseconds. See RFC 3261 for define.
+         * Value is in Integer format.
+         */
+        public static final int SIP_T1_TIMER = 7;
+
+        /**
+         * SIP T2 timer value in milliseconds.  See RFC 3261 for define.
+         * Value is in Integer format.
+         */
+        public static final int SIP_T2_TIMER  = 8;
+
+         /**
+         * SIP TF timer value in milliseconds.  See RFC 3261 for define.
+         * Value is in Integer format.
+         */
+        public static final int SIP_TF_TIMER = 9;
+
+        /**
+         * VoLTE status for VLT/s status of Enabled (1), or Disabled (0).
+         * Value is in Integer format.
+         */
+        public static final int VLT_SETTING_ENABLED = 10;
+
+        /**
+         * VoLTE status for LVC/s status of Enabled (1), or Disabled (0).
+         * Value is in Integer format.
+         */
+        public static final int LVC_SETTING_ENABLED = 11;
+        /**
+         * Domain Name for the device to populate the request URI for REGISTRATION.
+         * Value is in String format.
+         */
+        public static final int DOMAIN_NAME = 12;
+         /**
+         * Device Outgoing SMS based on either 3GPP or 3GPP2 standards.
+         * Value is in Integer format. 3GPP2(0), 3GPP(1)
+         */
+        public static final int SMS_FORMAT = 13;
+         /**
+         * Turns IMS ON/OFF on the device.
+         * Value is in Integer format. ON (1), OFF(0).
+         */
+        public static final int SMS_OVER_IP = 14;
+        /**
+         * Requested expiration for Published Online availability.
+         * Value is in Integer format.
+         */
+        public static final int PUBLISH_TIMER = 15;
+        /**
+         * Requested expiration for Published Offline availability.
+         * Value is in Integer format.
+         */
+        public static final int PUBLISH_TIMER_EXTENDED = 16;
+        /**
+         *
+         * Value is in Integer format.
+         */
+        public static final int CAPABILITY_DISCOVERY_ENABLED = 17;
+        /**
+         * Period of time the capability information of the  contact is cached on handset.
+         * Value is in Integer format.
+         */
+        public static final int CAPABILITIES_CACHE_EXPIRATION = 18;
+        /**
+         * Peiod of time the availability information of a contact is cached on device.
+         * Value is in Integer format.
+         */
+        public static final int AVAILABILITY_CACHE_EXPIRATION = 19;
+        /**
+         * Interval between successive capabilities polling.
+         * Value is in Integer format.
+         */
+        public static final int CAPABILITIES_POLL_INTERVAL = 20;
+        /**
+         * Minimum time between two published messages from the device.
+         * Value is in Integer format.
+         */
+        public static final int SOURCE_THROTTLE_PUBLISH = 21;
+        /**
+         * The Maximum number of MDNs contained in one Request Contained List.
+         * Value is in Integer format.
+         */
+        public static final int MAX_NUMENTRIES_IN_RCL = 22;
+        /**
+         * Expiration timer for subscription of a Request Contained List, used in capability
+         * polling.
+         * Value is in Integer format.
+         */
+        public static final int CAPAB_POLL_LIST_SUB_EXP = 23;
+        /**
+         * Applies compression to LIST Subscription.
+         * Value is in Integer format. Enable (1), Disable(0).
+         */
+        public static final int GZIP_FLAG = 24;
+        /**
+         * VOLTE Status for EAB/s status of Enabled (1), or Disabled (0).
+         * Value is in Integer format.
+         */
+        public static final int EAB_SETTING_ENABLED = 25;
+        /**
+         * Wi-Fi calling roaming status.
+         * Value is in Integer format. ON (1), OFF(0).
+         */
+        public static final int VOICE_OVER_WIFI_ROAMING = 26;
+        /**
+         * Wi-Fi calling modem - WfcModeFeatureValueConstants.
+         * Value is in Integer format.
+         */
+        public static final int VOICE_OVER_WIFI_MODE = 27;
+        /**
+         * VOLTE Status for voice over wifi status of Enabled (1), or Disabled (0).
+         * Value is in Integer format.
+         */
+        public static final int VOICE_OVER_WIFI_SETTING_ENABLED = 28;
+        /**
+         * Mobile data enabled.
+         * Value is in Integer format. On (1), OFF(0).
+         */
+        public static final int MOBILE_DATA_ENABLED = 29;
+        /**
+         * VoLTE user opted in status.
+         * Value is in Integer format. Opted-in (1) Opted-out (0).
+         */
+        public static final int VOLTE_USER_OPT_IN_STATUS = 30;
+        /**
+         * Proxy for Call Session Control Function(P-CSCF) address for Local-BreakOut(LBO).
+         * Value is in String format.
+         */
+        public static final int LBO_PCSCF_ADDRESS = 31;
+        /**
+         * Keep Alive Enabled for SIP.
+         * Value is in Integer format. On(1), OFF(0).
+         */
+        public static final int KEEP_ALIVE_ENABLED = 32;
+        /**
+         * Registration retry Base Time value in seconds.
+         * Value is in Integer format.
+         */
+        public static final int REGISTRATION_RETRY_BASE_TIME_SEC = 33;
+        /**
+         * Registration retry Max Time value in seconds.
+         * Value is in Integer format.
+         */
+        public static final int REGISTRATION_RETRY_MAX_TIME_SEC = 34;
+        /**
+         * Smallest RTP port for speech codec.
+         * Value is in integer format.
+         */
+        public static final int SPEECH_START_PORT = 35;
+        /**
+         * Largest RTP port for speech code.
+         * Value is in Integer format.
+         */
+        public static final int SPEECH_END_PORT = 36;
+        /**
+         * SIP Timer A's value in milliseconds. Timer A is the INVITE request
+         * retransmit interval, for UDP only.
+         * Value is in Integer format.
+         */
+        public static final int SIP_INVITE_REQ_RETX_INTERVAL_MSEC = 37;
+        /**
+         * SIP Timer B's value in milliseconds. Timer B is the wait time for
+         * INVITE message to be acknowledged.
+         * Value is in Integer format.
+         */
+        public static final int SIP_INVITE_RSP_WAIT_TIME_MSEC = 38;
+        /**
+         * SIP Timer D's value in milliseconds. Timer D is the wait time for
+         * response retransmits of the invite client transactions.
+         * Value is in Integer format.
+         */
+        public static final int SIP_INVITE_RSP_RETX_WAIT_TIME_MSEC = 39;
+        /**
+         * SIP Timer E's value in milliseconds. Timer E is the value Non-INVITE
+         * request retransmit interval, for UDP only.
+         * Value is in Integer format.
+         */
+        public static final int SIP_NON_INVITE_REQ_RETX_INTERVAL_MSEC = 40;
+        /**
+         * SIP Timer F's value in milliseconds. Timer F is the Non-INVITE transaction
+         * timeout timer.
+         * Value is in Integer format.
+         */
+        public static final int SIP_NON_INVITE_TXN_TIMEOUT_TIMER_MSEC = 41;
+        /**
+         * SIP Timer G's value in milliseconds. Timer G is the value of INVITE response
+         * retransmit interval.
+         * Value is in Integer format.
+         */
+        public static final int SIP_INVITE_RSP_RETX_INTERVAL_MSEC = 42;
+        /**
+         * SIP Timer H's value in milliseconds. Timer H is the value of wait time for
+         * ACK receipt.
+         * Value is in Integer format.
+         */
+        public static final int SIP_ACK_RECEIPT_WAIT_TIME_MSEC = 43;
+        /**
+         * SIP Timer I's value in milliseconds. Timer I is the value of wait time for
+         * ACK retransmits.
+         * Value is in Integer format.
+         */
+        public static final int SIP_ACK_RETX_WAIT_TIME_MSEC = 44;
+        /**
+         * SIP Timer J's value in milliseconds. Timer J is the value of wait time for
+         * non-invite request retransmission.
+         * Value is in Integer format.
+         */
+        public static final int SIP_NON_INVITE_REQ_RETX_WAIT_TIME_MSEC = 45;
+        /**
+         * SIP Timer K's value in milliseconds. Timer K is the value of wait time for
+         * non-invite response retransmits.
+         * Value is in Integer format.
+         */
+        public static final int SIP_NON_INVITE_RSP_RETX_WAIT_TIME_MSEC = 46;
+        /**
+         * AMR WB octet aligned dynamic payload type.
+         * Value is in Integer format.
+         */
+        public static final int AMR_WB_OCTET_ALIGNED_PT = 47;
+        /**
+         * AMR WB bandwidth efficient payload type.
+         * Value is in Integer format.
+         */
+        public static final int AMR_WB_BANDWIDTH_EFFICIENT_PT = 48;
+        /**
+         * AMR octet aligned dynamic payload type.
+         * Value is in Integer format.
+         */
+        public static final int AMR_OCTET_ALIGNED_PT = 49;
+        /**
+         * AMR bandwidth efficient payload type.
+         * Value is in Integer format.
+         */
+        public static final int AMR_BANDWIDTH_EFFICIENT_PT = 50;
+        /**
+         * DTMF WB payload type.
+         * Value is in Integer format.
+         */
+        public static final int DTMF_WB_PT = 51;
+        /**
+         * DTMF NB payload type.
+         * Value is in Integer format.
+         */
+        public static final int DTMF_NB_PT = 52;
+        /**
+         * AMR Default encoding mode.
+         * Value is in Integer format.
+         */
+        public static final int AMR_DEFAULT_MODE = 53;
+        /**
+         * SMS Public Service Identity.
+         * Value is in String format.
+         */
+        public static final int SMS_PSI = 54;
+        /**
+         * Video Quality - VideoQualityFeatureValuesConstants.
+         * Value is in Integer format.
+         */
+        public static final int VIDEO_QUALITY = 55;
+        /**
+         * LTE threshold.
+         * Handover from LTE to WiFi if LTE < THLTE1 and WiFi >= VOWT_A.
+         */
+        public static final int TH_LTE1 = 56;
+        /**
+         * LTE threshold.
+         * Handover from WiFi to LTE if LTE >= THLTE3 or (WiFi < VOWT_B and LTE >= THLTE2).
+         */
+        public static final int TH_LTE2 = 57;
+        /**
+         * LTE threshold.
+         * Handover from WiFi to LTE if LTE >= THLTE3 or (WiFi < VOWT_B and LTE >= THLTE2).
+         */
+        public static final int TH_LTE3 = 58;
+        /**
+         * 1x threshold.
+         * Handover from 1x to WiFi if 1x < TH1x
+         */
+        public static final int TH_1x = 59;
+        /**
+         * WiFi threshold.
+         * Handover from LTE to WiFi if LTE < THLTE1 and WiFi >= VOWT_A.
+         */
+        public static final int VOWT_A = 60;
+        /**
+         * WiFi threshold.
+         * Handover from WiFi to LTE if LTE >= THLTE3 or (WiFi < VOWT_B and LTE >= THLTE2).
+         */
+        public static final int VOWT_B = 61;
+        /**
+         * LTE ePDG timer.
+         * Device shall not handover back to LTE until the T_ePDG_LTE timer expires.
+         */
+        public static final int T_EPDG_LTE = 62;
+        /**
+         * WiFi ePDG timer.
+         * Device shall not handover back to WiFi until the T_ePDG_WiFi timer expires.
+         */
+        public static final int T_EPDG_WIFI = 63;
+        /**
+         * 1x ePDG timer.
+         * Device shall not re-register on 1x until the T_ePDG_1x timer expires.
+         */
+        public static final int T_EPDG_1X = 64;
+        /**
+         * MultiEndpoint status: Enabled (1), or Disabled (0).
+         * Value is in Integer format.
+         */
+        public static final int VICE_SETTING_ENABLED = 65;
+
+        // Expand the operator config items as needed here, need to change
+        // PROVISIONED_CONFIG_END after that.
+        public static final int PROVISIONED_CONFIG_END = VICE_SETTING_ENABLED;
+
+        // Expand the operator config items as needed here.
+    }
+
+    /**
+    * Defines IMS set operation status.
+    */
+    public static class OperationStatusConstants {
+        public static final int UNKNOWN = -1;
+        public static final int SUCCESS = 0;
+        public static final int FAILED =  1;
+        public static final int UNSUPPORTED_CAUSE_NONE = 2;
+        public static final int UNSUPPORTED_CAUSE_RAT = 3;
+        public static final int UNSUPPORTED_CAUSE_DISABLED = 4;
+    }
+
+    /**
+     * Defines IMS get operation values.
+     */
+    public static class OperationValuesConstants {
+        /**
+         * Values related to Video Quality
+         */
+        public static final int VIDEO_QUALITY_UNKNOWN = -1;
+        public static final int VIDEO_QUALITY_LOW = 0;
+        public static final int VIDEO_QUALITY_HIGH = 1;
+    }
+
+    /**
+     * Defines IMS video quality feature value.
+     */
+    public static class VideoQualityFeatureValuesConstants {
+        public static final int LOW = 0;
+        public static final int HIGH = 1;
+    }
+
+   /**
+    * Defines IMS feature value.
+    */
+    public static class FeatureValueConstants {
+        public static final int OFF = 0;
+        public static final int ON = 1;
+    }
+
+    /**
+     * Defines IMS feature value.
+     */
+    public static class WfcModeFeatureValueConstants {
+        public static final int WIFI_ONLY = 0;
+        public static final int CELLULAR_PREFERRED = 1;
+        public static final int WIFI_PREFERRED = 2;
+    }
+
+    public ImsConfig(IImsConfig iconfig, Context context) {
+        if (DBG) Rlog.d(TAG, "ImsConfig creates");
+        miConfig = iconfig;
+        mContext = context;
+    }
+
+    /**
+     * Gets the provisioned value for IMS service/capabilities parameters used by IMS stack.
+     * This function should not be called from the mainthread as it could block the
+     * mainthread.
+     *
+     * @param item, as defined in com.android.ims.ImsConfig#ConfigConstants.
+     * @return the value in Integer format.
+     *
+     * @throws ImsException if calling the IMS service results in an error.
+     */
+    public int getProvisionedValue(int item) throws ImsException {
+        int ret = 0;
+        try {
+            ret = miConfig.getProvisionedValue(item);
+        }  catch (RemoteException e) {
+            throw new ImsException("getValue()", e,
+                    ImsReasonInfo.CODE_LOCAL_SERVICE_UNAVAILABLE);
+        }
+        if (DBG) Rlog.d(TAG, "getProvisionedValue(): item = " + item + ", ret =" + ret);
+
+        return ret;
+    }
+
+    /**
+     * Gets the provisioned value for IMS service/capabilities parameters used by IMS stack.
+     * This function should not be called from the mainthread as it could block the
+     * mainthread.
+     *
+     * @param item, as defined in com.android.ims.ImsConfig#ConfigConstants.
+     * @return value in String format.
+     *
+     * @throws ImsException if calling the IMS service results in an error.
+     */
+    public String getProvisionedStringValue(int item) throws ImsException {
+        String ret = "Unknown";
+        try {
+            ret = miConfig.getProvisionedStringValue(item);
+        }  catch (RemoteException e) {
+            throw new ImsException("getProvisionedStringValue()", e,
+                    ImsReasonInfo.CODE_LOCAL_SERVICE_UNAVAILABLE);
+        }
+        if (DBG) Rlog.d(TAG, "getProvisionedStringValue(): item = " + item + ", ret =" + ret);
+
+        return ret;
+    }
+
+    /**
+     * Sets the value for IMS service/capabilities parameters by
+     * the operator device management entity.
+     * This function should not be called from main thread as it could block
+     * mainthread.
+     *
+     * @param item, as defined in com.android.ims.ImsConfig#ConfigConstants.
+     * @param value in Integer format.
+     * @return as defined in com.android.ims.ImsConfig#OperationStatusConstants
+     *
+     * @throws ImsException if calling the IMS service results in an error.
+     */
+    public int setProvisionedValue(int item, int value)
+            throws ImsException {
+        int ret = OperationStatusConstants.UNKNOWN;
+        if (DBG) {
+            Rlog.d(TAG, "setProvisionedValue(): item = " + item +
+                    "value = " + value);
+        }
+        try {
+            ret = miConfig.setProvisionedValue(item, value);
+        }  catch (RemoteException e) {
+            throw new ImsException("setProvisionedValue()", e,
+                    ImsReasonInfo.CODE_LOCAL_SERVICE_UNAVAILABLE);
+        }
+        if (DBG) {
+            Rlog.d(TAG, "setProvisionedValue(): item = " + item +
+                    " value = " + value + " ret = " + ret);
+        }
+        return ret;
+    }
+
+    /**
+     * Sets the value for IMS service/capabilities parameters by
+     * the operator device management entity.
+     * This function should not be called from main thread as it could block
+     * mainthread.
+     *
+     * @param item, as defined in com.android.ims.ImsConfig#ConfigConstants.
+     * @param value in String format.
+     * @return as defined in com.android.ims.ImsConfig#OperationStatusConstants
+     *
+     * @throws ImsException if calling the IMS service results in an error.
+     */
+    public int setProvisionedStringValue(int item, String value)
+            throws ImsException {
+        int ret = OperationStatusConstants.UNKNOWN;
+        try {
+            ret = miConfig.setProvisionedStringValue(item, value);
+        }  catch (RemoteException e) {
+            throw new ImsException("setProvisionedStringValue()", e,
+                    ImsReasonInfo.CODE_LOCAL_SERVICE_UNAVAILABLE);
+        }
+        if (DBG) {
+            Rlog.d(TAG, "setProvisionedStringValue(): item = " + item +
+                    ", value =" + value);
+        }
+        return ret;
+    }
+
+    /**
+     * Gets the value for IMS feature item for specified network type.
+     *
+     * @param feature, defined as in FeatureConstants.
+     * @param network, defined as in android.telephony.TelephonyManager#NETWORK_TYPE_XXX.
+     * @param listener, provided to be notified for the feature on/off status.
+     * @return void
+     *
+     * @throws ImsException if calling the IMS service results in an error.
+     */
+    public void getFeatureValue(int feature, int network,
+            ImsConfigListener listener) throws ImsException {
+        if (DBG) {
+            Rlog.d(TAG, "getFeatureValue: feature = " + feature + ", network =" + network +
+                    ", listener =" + listener);
+        }
+        try {
+            miConfig.getFeatureValue(feature, network, listener);
+        } catch (RemoteException e) {
+            throw new ImsException("getFeatureValue()", e,
+                    ImsReasonInfo.CODE_LOCAL_SERVICE_UNAVAILABLE);
+        }
+    }
+
+    /**
+     * Sets the value for IMS feature item for specified network type.
+     *
+     * @param feature, as defined in FeatureConstants.
+     * @param network, as defined in android.telephony.TelephonyManager#NETWORK_TYPE_XXX.
+     * @param value, as defined in FeatureValueConstants.
+     * @param listener, provided if caller needs to be notified for set result.
+     * @return void
+     *
+     * @throws ImsException if calling the IMS service results in an error.
+     */
+    public void setFeatureValue(int feature, int network, int value,
+            ImsConfigListener listener) throws ImsException {
+        if (DBG) {
+            Rlog.d(TAG, "setFeatureValue: feature = " + feature + ", network =" + network +
+                    ", value =" + value + ", listener =" + listener);
+        }
+        try {
+            miConfig.setFeatureValue(feature, network, value, listener);
+        } catch (RemoteException e) {
+            throw new ImsException("setFeatureValue()", e,
+                    ImsReasonInfo.CODE_LOCAL_SERVICE_UNAVAILABLE);
+        }
+    }
+}
diff --git a/telephony/java/com/android/ims/ImsException.java b/telephony/java/com/android/ims/ImsException.java
new file mode 100644
index 0000000..74b20f4
--- /dev/null
+++ b/telephony/java/com/android/ims/ImsException.java
@@ -0,0 +1,52 @@
+/*
+ * 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 com.android.ims;
+
+/**
+ * This class defines a general IMS-related exception.
+ *
+ * @hide
+ */
+public class ImsException extends Exception {
+
+    /**
+     * Refer to CODE_LOCAL_* in {@link ImsReasonInfo}
+     */
+    private int mCode;
+
+    public ImsException() {
+    }
+
+    public ImsException(String message, int code) {
+        super(message + ", code = " + code);
+        mCode = code;
+    }
+
+    public ImsException(String message, Throwable cause, int code) {
+        super(message, cause);
+        mCode = code;
+    }
+
+    /**
+     * Gets the detailed exception code when ImsException is throwed
+     *
+     * @return the exception code in {@link ImsReasonInfo}
+     */
+    public int getCode() {
+        return mCode;
+    }
+}
diff --git a/telephony/java/com/android/ims/ImsUtInterface.java b/telephony/java/com/android/ims/ImsUtInterface.java
new file mode 100644
index 0000000..5984e78
--- /dev/null
+++ b/telephony/java/com/android/ims/ImsUtInterface.java
@@ -0,0 +1,179 @@
+/*
+ * 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 com.android.ims;
+
+import android.os.Message;
+
+/**
+ * Provides APIs for the supplementary service settings using IMS (Ut interface).
+ * It is created from 3GPP TS 24.623 (XCAP(XML Configuration Access Protocol)
+ * over the Ut interface for manipulating supplementary services).
+ *
+ * @hide
+ */
+public interface ImsUtInterface {
+    /**
+     * Actions
+     * @hide
+     */
+    public static final int ACTION_DEACTIVATION = 0;
+    public static final int ACTION_ACTIVATION = 1;
+    public static final int ACTION_REGISTRATION = 3;
+    public static final int ACTION_ERASURE = 4;
+    public static final int ACTION_INTERROGATION = 5;
+
+    /**
+     * OIR (Originating Identification Restriction, 3GPP TS 24.607)
+     * OIP (Originating Identification Presentation, 3GPP TS 24.607)
+     * TIR (Terminating Identification Restriction, 3GPP TS 24.608)
+     * TIP (Terminating Identification Presentation, 3GPP TS 24.608)
+     */
+    public static final int OIR_DEFAULT = 0;    // "user subscription default value"
+    public static final int OIR_PRESENTATION_RESTRICTED = 1;
+    public static final int OIR_PRESENTATION_NOT_RESTRICTED = 2;
+
+    /**
+     * CW (Communication Waiting, 3GPP TS 24.615)
+     */
+
+    /**
+     * CDIV (Communication Diversion, 3GPP TS 24.604)
+     *     actions: target, no reply timer
+     */
+    public static final int CDIV_CF_UNCONDITIONAL = 0;
+    public static final int CDIV_CF_BUSY = 1;
+    public static final int CDIV_CF_NO_REPLY = 2;
+    public static final int CDIV_CF_NOT_REACHABLE = 3;
+    // For CS service code: 002
+    public static final int CDIV_CF_ALL = 4;
+    // For CS service code: 004
+    public static final int CDIV_CF_ALL_CONDITIONAL = 5;
+    // It's only supported in the IMS service (CS does not define it).
+    // IR.92 recommends that an UE activates both the CFNRc and the CFNL
+    // (CDIV using condition not-registered) to the same target.
+    public static final int CDIV_CF_NOT_LOGGED_IN = 6;
+
+    /**
+     * CB (Communication Barring, 3GPP TS 24.611)
+     */
+    // Barring of All Incoming Calls
+    public static final int CB_BAIC = 1;
+    // Barring of All Outgoing Calls
+    public static final int CB_BAOC = 2;
+    // Barring of Outgoing International Calls
+    public static final int CB_BOIC = 3;
+    // Barring of Outgoing International Calls - excluding Home Country
+    public static final int CB_BOIC_EXHC = 4;
+    // Barring of Incoming Calls - when roaming
+    public static final int CB_BIC_WR = 5;
+    // Barring of Anonymous Communication Rejection (ACR) - a particular case of ICB service
+    public static final int CB_BIC_ACR = 6;
+    // Barring of All Calls
+    public static final int CB_BA_ALL = 7;
+    // Barring of Outgoing Services (Service Code 333 - 3GPP TS 22.030 Table B-1)
+    public static final int CB_BA_MO = 8;
+    // Barring of Incoming Services (Service Code 353 - 3GPP TS 22.030 Table B-1)
+    public static final int CB_BA_MT = 9;
+    // Barring of Specific Incoming calls
+    public static final int CB_BS_MT = 10;
+
+    /**
+     * Invalid result value.
+     */
+    public static final int INVALID = (-1);
+
+
+
+    /**
+     * Operations for the supplementary service configuration
+     */
+
+    /**
+     * Retrieves the configuration of the call barring.
+     * The return value of ((AsyncResult)result.obj) is an array of {@link ImsSsInfo}.
+     */
+    public void queryCallBarring(int cbType, Message result);
+
+    /**
+     * Retrieves the configuration of the call forward.
+     * The return value of ((AsyncResult)result.obj) is an array of {@link ImsCallForwardInfo}.
+     */
+    public void queryCallForward(int condition, String number, Message result);
+
+    /**
+     * Retrieves the configuration of the call waiting.
+     * The return value of ((AsyncResult)result.obj) is an array of {@link ImsSsInfo}.
+     */
+    public void queryCallWaiting(Message result);
+
+    /**
+     * Retrieves the default CLIR setting.
+     */
+    public void queryCLIR(Message result);
+
+    /**
+     * Retrieves the CLIP call setting.
+     */
+    public void queryCLIP(Message result);
+
+    /**
+     * Retrieves the COLR call setting.
+     */
+    public void queryCOLR(Message result);
+
+    /**
+     * Retrieves the COLP call setting.
+     */
+    public void queryCOLP(Message result);
+
+    /**
+     * Modifies the configuration of the call barring.
+     */
+    public void updateCallBarring(int cbType, int action,
+            Message result, String[] barrList);
+
+    /**
+     * Modifies the configuration of the call forward.
+     */
+    public void updateCallForward(int action, int condition, String number,
+            int serviceClass, int timeSeconds, Message result);
+
+    /**
+     * Modifies the configuration of the call waiting.
+     */
+    public void updateCallWaiting(boolean enable, int serviceClass, Message result);
+
+    /**
+     * Updates the configuration of the CLIR supplementary service.
+     */
+    public void updateCLIR(int clirMode, Message result);
+
+    /**
+     * Updates the configuration of the CLIP supplementary service.
+     */
+    public void updateCLIP(boolean enable, Message result);
+
+    /**
+     * Updates the configuration of the COLR supplementary service.
+     */
+    public void updateCOLR(int presentation, Message result);
+
+    /**
+     * Updates the configuration of the COLP supplementary service.
+     */
+    public void updateCOLP(boolean enable, Message result);
+}
diff --git a/telephony/java/com/android/ims/internal/IImsServiceFeatureListener.aidl b/telephony/java/com/android/ims/internal/IImsServiceFeatureListener.aidl
index 82a13dc..df10700 100644
--- a/telephony/java/com/android/ims/internal/IImsServiceFeatureListener.aidl
+++ b/telephony/java/com/android/ims/internal/IImsServiceFeatureListener.aidl
@@ -17,7 +17,8 @@
 package com.android.ims.internal;
 
 /**
-*  Interface from ImsResolver to ImsServiceProxy in ImsManager.
+ *  Interface from ImsResolver to ImsServiceProxy in ImsManager.
+ * Callback to ImsManager when a feature changes in the ImsServiceController.
  * {@hide}
  */
 oneway interface IImsServiceFeatureListener {
diff --git a/telephony/java/com/android/ims/internal/ImsCallSession.java b/telephony/java/com/android/ims/internal/ImsCallSession.java
new file mode 100644
index 0000000..8196b23
--- /dev/null
+++ b/telephony/java/com/android/ims/internal/ImsCallSession.java
@@ -0,0 +1,1290 @@
+/*
+ * 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 com.android.ims.internal;
+
+import android.os.Message;
+import android.os.RemoteException;
+
+import java.util.Objects;
+
+import android.telephony.ims.stub.ImsCallSessionListenerImplBase;
+import android.util.Log;
+import com.android.ims.ImsCallProfile;
+import com.android.ims.ImsConferenceState;
+import com.android.ims.ImsReasonInfo;
+import com.android.ims.ImsStreamMediaProfile;
+import com.android.ims.ImsSuppServiceNotification;
+
+/**
+ * Provides the call initiation/termination, and media exchange between two IMS endpoints.
+ * It directly communicates with IMS service which implements the IMS protocol behavior.
+ *
+ * @hide
+ */
+public class ImsCallSession {
+    private static final String TAG = "ImsCallSession";
+
+    /**
+     * Defines IMS call session state.
+     */
+    public static class State {
+        public static final int IDLE = 0;
+        public static final int INITIATED = 1;
+        public static final int NEGOTIATING = 2;
+        public static final int ESTABLISHING = 3;
+        public static final int ESTABLISHED = 4;
+
+        public static final int RENEGOTIATING = 5;
+        public static final int REESTABLISHING = 6;
+
+        public static final int TERMINATING = 7;
+        public static final int TERMINATED = 8;
+
+        public static final int INVALID = (-1);
+
+        /**
+         * Converts the state to string.
+         */
+        public static String toString(int state) {
+            switch (state) {
+                case IDLE:
+                    return "IDLE";
+                case INITIATED:
+                    return "INITIATED";
+                case NEGOTIATING:
+                    return "NEGOTIATING";
+                case ESTABLISHING:
+                    return "ESTABLISHING";
+                case ESTABLISHED:
+                    return "ESTABLISHED";
+                case RENEGOTIATING:
+                    return "RENEGOTIATING";
+                case REESTABLISHING:
+                    return "REESTABLISHING";
+                case TERMINATING:
+                    return "TERMINATING";
+                case TERMINATED:
+                    return "TERMINATED";
+                default:
+                    return "UNKNOWN";
+            }
+        }
+
+        private State() {
+        }
+    }
+
+    /**
+     * Listener for events relating to an IMS session, such as when a session is being
+     * recieved ("on ringing") or a call is outgoing ("on calling").
+     * <p>Many of these events are also received by {@link ImsCall.Listener}.</p>
+     */
+    public static class Listener {
+        /**
+         * Called when a request is sent out to initiate a new session
+         * and 1xx response is received from the network.
+         *
+         * @param session the session object that carries out the IMS session
+         */
+        public void callSessionProgressing(ImsCallSession session,
+                ImsStreamMediaProfile profile) {
+            // no-op
+        }
+
+        /**
+         * Called when the session is established.
+         *
+         * @param session the session object that carries out the IMS session
+         */
+        public void callSessionStarted(ImsCallSession session,
+                ImsCallProfile profile) {
+            // no-op
+        }
+
+        /**
+         * Called when the session establishment is failed.
+         *
+         * @param session the session object that carries out the IMS session
+         * @param reasonInfo detailed reason of the session establishment failure
+         */
+        public void callSessionStartFailed(ImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+        }
+
+        /**
+         * Called when the session is terminated.
+         *
+         * @param session the session object that carries out the IMS session
+         * @param reasonInfo detailed reason of the session termination
+         */
+        public void callSessionTerminated(ImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+        }
+
+        /**
+         * Called when the session is in hold.
+         *
+         * @param session the session object that carries out the IMS session
+         */
+        public void callSessionHeld(ImsCallSession session,
+                ImsCallProfile profile) {
+        }
+
+        /**
+         * Called when the session hold is failed.
+         *
+         * @param session the session object that carries out the IMS session
+         * @param reasonInfo detailed reason of the session hold failure
+         */
+        public void callSessionHoldFailed(ImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+        }
+
+        /**
+         * Called when the session hold is received from the remote user.
+         *
+         * @param session the session object that carries out the IMS session
+         */
+        public void callSessionHoldReceived(ImsCallSession session,
+                ImsCallProfile profile) {
+        }
+
+        /**
+         * Called when the session resume is done.
+         *
+         * @param session the session object that carries out the IMS session
+         */
+        public void callSessionResumed(ImsCallSession session,
+                ImsCallProfile profile) {
+        }
+
+        /**
+         * Called when the session resume is failed.
+         *
+         * @param session the session object that carries out the IMS session
+         * @param reasonInfo detailed reason of the session resume failure
+         */
+        public void callSessionResumeFailed(ImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+        }
+
+        /**
+         * Called when the session resume is received from the remote user.
+         *
+         * @param session the session object that carries out the IMS session
+         */
+        public void callSessionResumeReceived(ImsCallSession session,
+                ImsCallProfile profile) {
+        }
+
+        /**
+         * Called when the session merge has been started.  At this point, the {@code newSession}
+         * represents the session which has been initiated to the IMS conference server for the
+         * new merged conference.
+         *
+         * @param session the session object that carries out the IMS session
+         * @param newSession the session object that is merged with an active & hold session
+         */
+        public void callSessionMergeStarted(ImsCallSession session,
+                ImsCallSession newSession, ImsCallProfile profile) {
+        }
+
+        /**
+         * Called when the session merge is successful and the merged session is active.
+         *
+         * @param session the session object that carries out the IMS session
+         */
+        public void callSessionMergeComplete(ImsCallSession session) {
+        }
+
+        /**
+         * Called when the session merge has failed.
+         *
+         * @param session the session object that carries out the IMS session
+         * @param reasonInfo detailed reason of the call merge failure
+         */
+        public void callSessionMergeFailed(ImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+        }
+
+        /**
+         * Called when the session is updated (except for hold/unhold).
+         *
+         * @param session the session object that carries out the IMS session
+         */
+        public void callSessionUpdated(ImsCallSession session,
+                ImsCallProfile profile) {
+        }
+
+        /**
+         * Called when the session update is failed.
+         *
+         * @param session the session object that carries out the IMS session
+         * @param reasonInfo detailed reason of the session update failure
+         */
+        public void callSessionUpdateFailed(ImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+        }
+
+        /**
+         * Called when the session update is received from the remote user.
+         *
+         * @param session the session object that carries out the IMS session
+         */
+        public void callSessionUpdateReceived(ImsCallSession session,
+                ImsCallProfile profile) {
+            // no-op
+        }
+
+        /**
+         * Called when the session is extended to the conference session.
+         *
+         * @param session the session object that carries out the IMS session
+         * @param newSession the session object that is extended to the conference
+         *      from the active session
+         */
+        public void callSessionConferenceExtended(ImsCallSession session,
+                ImsCallSession newSession, ImsCallProfile profile) {
+        }
+
+        /**
+         * Called when the conference extension is failed.
+         *
+         * @param session the session object that carries out the IMS session
+         * @param reasonInfo detailed reason of the conference extension failure
+         */
+        public void callSessionConferenceExtendFailed(ImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+        }
+
+        /**
+         * Called when the conference extension is received from the remote user.
+         *
+         * @param session the session object that carries out the IMS session
+         */
+        public void callSessionConferenceExtendReceived(ImsCallSession session,
+                ImsCallSession newSession, ImsCallProfile profile) {
+            // no-op
+        }
+
+        /**
+         * Called when the invitation request of the participants is delivered to the conference
+         * server.
+         *
+         * @param session the session object that carries out the IMS session
+         */
+        public void callSessionInviteParticipantsRequestDelivered(ImsCallSession session) {
+            // no-op
+        }
+
+        /**
+         * Called when the invitation request of the participants is failed.
+         *
+         * @param session the session object that carries out the IMS session
+         * @param reasonInfo detailed reason of the conference invitation failure
+         */
+        public void callSessionInviteParticipantsRequestFailed(ImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+            // no-op
+        }
+
+        /**
+         * Called when the removal request of the participants is delivered to the conference
+         * server.
+         *
+         * @param session the session object that carries out the IMS session
+         */
+        public void callSessionRemoveParticipantsRequestDelivered(ImsCallSession session) {
+            // no-op
+        }
+
+        /**
+         * Called when the removal request of the participants is failed.
+         *
+         * @param session the session object that carries out the IMS session
+         * @param reasonInfo detailed reason of the conference removal failure
+         */
+        public void callSessionRemoveParticipantsRequestFailed(ImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+            // no-op
+        }
+
+        /**
+         * Called when the conference state is updated.
+         *
+         * @param session the session object that carries out the IMS session
+         */
+        public void callSessionConferenceStateUpdated(ImsCallSession session,
+                ImsConferenceState state) {
+            // no-op
+        }
+
+        /**
+         * Called when the USSD message is received from the network.
+         *
+         * @param mode mode of the USSD message (REQUEST / NOTIFY)
+         * @param ussdMessage USSD message
+         */
+        public void callSessionUssdMessageReceived(ImsCallSession session,
+                int mode, String ussdMessage) {
+            // no-op
+        }
+
+        /**
+         * Called when session access technology changes
+         *
+         * @param session IMS session object
+         * @param srcAccessTech original access technology
+         * @param targetAccessTech new access technology
+         * @param reasonInfo
+         */
+        public void callSessionHandover(ImsCallSession session,
+                                 int srcAccessTech, int targetAccessTech,
+                                 ImsReasonInfo reasonInfo) {
+            // no-op
+        }
+
+        /**
+         * Called when session access technology change fails
+         *
+         * @param session IMS session object
+         * @param srcAccessTech original access technology
+         * @param targetAccessTech new access technology
+         * @param reasonInfo handover failure reason
+         */
+        public void callSessionHandoverFailed(ImsCallSession session,
+                                       int srcAccessTech, int targetAccessTech,
+                                       ImsReasonInfo reasonInfo) {
+            // no-op
+        }
+
+        /**
+         * Called when TTY mode of remote party changed
+         *
+         * @param session IMS session object
+         * @param mode TTY mode of remote party
+         */
+        public void callSessionTtyModeReceived(ImsCallSession session,
+                                       int mode) {
+            // no-op
+        }
+
+        /**
+         * Notifies of a change to the multiparty state for this {@code ImsCallSession}.
+         *
+         * @param session The call session.
+         * @param isMultiParty {@code true} if the session became multiparty, {@code false}
+         *      otherwise.
+         */
+        public void callSessionMultipartyStateChanged(ImsCallSession session,
+                boolean isMultiParty) {
+            // no-op
+        }
+
+        /**
+         * Called when the session supplementary service is received
+         *
+         * @param session the session object that carries out the IMS session
+         */
+        public void callSessionSuppServiceReceived(ImsCallSession session,
+                ImsSuppServiceNotification suppServiceInfo) {
+        }
+    }
+
+    private final IImsCallSession miSession;
+    private boolean mClosed = false;
+    private Listener mListener;
+
+    public ImsCallSession(IImsCallSession iSession) {
+        miSession = iSession;
+
+        if (iSession != null) {
+            try {
+                iSession.setListener(new IImsCallSessionListenerProxy());
+            } catch (RemoteException e) {
+            }
+        } else {
+            mClosed = true;
+        }
+    }
+
+    public ImsCallSession(IImsCallSession iSession, Listener listener) {
+        this(iSession);
+        setListener(listener);
+    }
+
+    /**
+     * Closes this object. This object is not usable after being closed.
+     */
+    public synchronized void close() {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.close();
+            mClosed = true;
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Gets the call ID of the session.
+     *
+     * @return the call ID
+     */
+    public String getCallId() {
+        if (mClosed) {
+            return null;
+        }
+
+        try {
+            return miSession.getCallId();
+        } catch (RemoteException e) {
+            return null;
+        }
+    }
+
+    /**
+     * Gets the call profile that this session is associated with
+     *
+     * @return the call profile that this session is associated with
+     */
+    public ImsCallProfile getCallProfile() {
+        if (mClosed) {
+            return null;
+        }
+
+        try {
+            return miSession.getCallProfile();
+        } catch (RemoteException e) {
+            return null;
+        }
+    }
+
+    /**
+     * Gets the local call profile that this session is associated with
+     *
+     * @return the local call profile that this session is associated with
+     */
+    public ImsCallProfile getLocalCallProfile() {
+        if (mClosed) {
+            return null;
+        }
+
+        try {
+            return miSession.getLocalCallProfile();
+        } catch (RemoteException e) {
+            return null;
+        }
+    }
+
+    /**
+     * Gets the remote call profile that this session is associated with
+     *
+     * @return the remote call profile that this session is associated with
+     */
+    public ImsCallProfile getRemoteCallProfile() {
+        if (mClosed) {
+            return null;
+        }
+
+        try {
+            return miSession.getRemoteCallProfile();
+        } catch (RemoteException e) {
+            return null;
+        }
+    }
+
+    /**
+     * Gets the video call provider for the session.
+     *
+     * @return The video call provider.
+     */
+    public IImsVideoCallProvider getVideoCallProvider() {
+        if (mClosed) {
+            return null;
+        }
+
+        try {
+            return miSession.getVideoCallProvider();
+        } catch (RemoteException e) {
+            return null;
+        }
+    }
+
+    /**
+     * Gets the value associated with the specified property of this session.
+     *
+     * @return the string value associated with the specified property
+     */
+    public String getProperty(String name) {
+        if (mClosed) {
+            return null;
+        }
+
+        try {
+            return miSession.getProperty(name);
+        } catch (RemoteException e) {
+            return null;
+        }
+    }
+
+    /**
+     * Gets the session state.
+     * The value returned must be one of the states in {@link State}.
+     *
+     * @return the session state
+     */
+    public int getState() {
+        if (mClosed) {
+            return State.INVALID;
+        }
+
+        try {
+            return miSession.getState();
+        } catch (RemoteException e) {
+            return State.INVALID;
+        }
+    }
+
+    /**
+     * Determines if the {@link ImsCallSession} is currently alive (e.g. not in a terminated or
+     * closed state).
+     *
+     * @return {@code True} if the session is alive.
+     */
+    public boolean isAlive() {
+        if (mClosed) {
+            return false;
+        }
+
+        int state = getState();
+        switch (state) {
+            case State.IDLE:
+            case State.INITIATED:
+            case State.NEGOTIATING:
+            case State.ESTABLISHING:
+            case State.ESTABLISHED:
+            case State.RENEGOTIATING:
+            case State.REESTABLISHING:
+                return true;
+            default:
+                return false;
+        }
+    }
+
+    /**
+     * Gets the native IMS call session.
+     * @hide
+     */
+    public IImsCallSession getSession() {
+        return miSession;
+    }
+
+    /**
+     * Checks if the session is in call.
+     *
+     * @return true if the session is in call
+     */
+    public boolean isInCall() {
+        if (mClosed) {
+            return false;
+        }
+
+        try {
+            return miSession.isInCall();
+        } catch (RemoteException e) {
+            return false;
+        }
+    }
+
+    /**
+     * Sets the listener to listen to the session events. A {@link ImsCallSession}
+     * can only hold one listener at a time. Subsequent calls to this method
+     * override the previous listener.
+     *
+     * @param listener to listen to the session events of this object
+     */
+    public void setListener(Listener listener) {
+        mListener = listener;
+    }
+
+    /**
+     * Mutes or unmutes the mic for the active call.
+     *
+     * @param muted true if the call is muted, false otherwise
+     */
+    public void setMute(boolean muted) {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.setMute(muted);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Initiates an IMS call with the specified target and call profile.
+     * The session listener is called back upon defined session events.
+     * The method is only valid to call when the session state is in
+     * {@link ImsCallSession.State#IDLE}.
+     *
+     * @param callee dialed string to make the call to
+     * @param profile call profile to make the call with the specified service type,
+     *      call type and media information
+     * @see Listener#callSessionStarted, Listener#callSessionStartFailed
+     */
+    public void start(String callee, ImsCallProfile profile) {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.start(callee, profile);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Initiates an IMS conference call with the specified target and call profile.
+     * The session listener is called back upon defined session events.
+     * The method is only valid to call when the session state is in
+     * {@link ImsCallSession.State#IDLE}.
+     *
+     * @param participants participant list to initiate an IMS conference call
+     * @param profile call profile to make the call with the specified service type,
+     *      call type and media information
+     * @see Listener#callSessionStarted, Listener#callSessionStartFailed
+     */
+    public void start(String[] participants, ImsCallProfile profile) {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.startConference(participants, profile);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Accepts an incoming call or session update.
+     *
+     * @param callType call type specified in {@link ImsCallProfile} to be answered
+     * @param profile stream media profile {@link ImsStreamMediaProfile} to be answered
+     * @see Listener#callSessionStarted
+     */
+    public void accept(int callType, ImsStreamMediaProfile profile) {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.accept(callType, profile);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Rejects an incoming call or session update.
+     *
+     * @param reason reason code to reject an incoming call
+     * @see Listener#callSessionStartFailed
+     */
+    public void reject(int reason) {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.reject(reason);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Terminates a call.
+     *
+     * @see Listener#callSessionTerminated
+     */
+    public void terminate(int reason) {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.terminate(reason);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Puts a call on hold. When it succeeds, {@link Listener#callSessionHeld} is called.
+     *
+     * @param profile stream media profile {@link ImsStreamMediaProfile} to hold the call
+     * @see Listener#callSessionHeld, Listener#callSessionHoldFailed
+     */
+    public void hold(ImsStreamMediaProfile profile) {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.hold(profile);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Continues a call that's on hold. When it succeeds,
+     * {@link Listener#callSessionResumed} is called.
+     *
+     * @param profile stream media profile {@link ImsStreamMediaProfile} to resume the call
+     * @see Listener#callSessionResumed, Listener#callSessionResumeFailed
+     */
+    public void resume(ImsStreamMediaProfile profile) {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.resume(profile);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Merges the active & hold call. When it succeeds,
+     * {@link Listener#callSessionMergeStarted} is called.
+     *
+     * @see Listener#callSessionMergeStarted , Listener#callSessionMergeFailed
+     */
+    public void merge() {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.merge();
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Updates the current call's properties (ex. call mode change: video upgrade / downgrade).
+     *
+     * @param callType call type specified in {@link ImsCallProfile} to be updated
+     * @param profile stream media profile {@link ImsStreamMediaProfile} to be updated
+     * @see Listener#callSessionUpdated, Listener#callSessionUpdateFailed
+     */
+    public void update(int callType, ImsStreamMediaProfile profile) {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.update(callType, profile);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Extends this call to the conference call with the specified recipients.
+     *
+     * @param participants list to be invited to the conference call after extending the call
+     * @see Listener#callSessionConferenceExtended
+     * @see Listener#callSessionConferenceExtendFailed
+     */
+    public void extendToConference(String[] participants) {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.extendToConference(participants);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Requests the conference server to invite an additional participants to the conference.
+     *
+     * @param participants list to be invited to the conference call
+     * @see Listener#callSessionInviteParticipantsRequestDelivered
+     * @see Listener#callSessionInviteParticipantsRequestFailed
+     */
+    public void inviteParticipants(String[] participants) {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.inviteParticipants(participants);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Requests the conference server to remove the specified participants from the conference.
+     *
+     * @param participants participant list to be removed from the conference call
+     * @see Listener#callSessionRemoveParticipantsRequestDelivered
+     * @see Listener#callSessionRemoveParticipantsRequestFailed
+     */
+    public void removeParticipants(String[] participants) {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.removeParticipants(participants);
+        } catch (RemoteException e) {
+        }
+    }
+
+
+    /**
+     * Sends a DTMF code. According to <a href="http://tools.ietf.org/html/rfc2833">RFC 2833</a>,
+     * event 0 ~ 9 maps to decimal value 0 ~ 9, '*' to 10, '#' to 11, event 'A' ~ 'D' to 12 ~ 15,
+     * and event flash to 16. Currently, event flash is not supported.
+     *
+     * @param c the DTMF to send. '0' ~ '9', 'A' ~ 'D', '*', '#' are valid inputs.
+     */
+    public void sendDtmf(char c, Message result) {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.sendDtmf(c, result);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Starts a DTMF code. According to <a href="http://tools.ietf.org/html/rfc2833">RFC 2833</a>,
+     * event 0 ~ 9 maps to decimal value 0 ~ 9, '*' to 10, '#' to 11, event 'A' ~ 'D' to 12 ~ 15,
+     * and event flash to 16. Currently, event flash is not supported.
+     *
+     * @param c the DTMF to send. '0' ~ '9', 'A' ~ 'D', '*', '#' are valid inputs.
+     */
+    public void startDtmf(char c) {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.startDtmf(c);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Stops a DTMF code.
+     */
+    public void stopDtmf() {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.stopDtmf();
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Sends an USSD message.
+     *
+     * @param ussdMessage USSD message to send
+     */
+    public void sendUssd(String ussdMessage) {
+        if (mClosed) {
+            return;
+        }
+
+        try {
+            miSession.sendUssd(ussdMessage);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Determines if the session is multiparty.
+     *
+     * @return {@code True} if the session is multiparty.
+     */
+    public boolean isMultiparty() {
+        if (mClosed) {
+            return false;
+        }
+
+        try {
+            return miSession.isMultiparty();
+        } catch (RemoteException e) {
+            return false;
+        }
+    }
+
+    /**
+     * A listener type for receiving notification on IMS call session events.
+     * When an event is generated for an {@link IImsCallSession},
+     * the application is notified by having one of the methods called on
+     * the {@link IImsCallSessionListener}.
+     */
+    private class IImsCallSessionListenerProxy extends ImsCallSessionListenerImplBase {
+        /**
+         * Notifies the result of the basic session operation (setup / terminate).
+         */
+        @Override
+        public void callSessionProgressing(IImsCallSession session,
+                ImsStreamMediaProfile profile) {
+            if (mListener != null) {
+                mListener.callSessionProgressing(ImsCallSession.this, profile);
+            }
+        }
+
+        @Override
+        public void callSessionStarted(IImsCallSession session,
+                ImsCallProfile profile) {
+            if (mListener != null) {
+                mListener.callSessionStarted(ImsCallSession.this, profile);
+            }
+        }
+
+        @Override
+        public void callSessionStartFailed(IImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+            if (mListener != null) {
+                mListener.callSessionStartFailed(ImsCallSession.this, reasonInfo);
+            }
+        }
+
+        @Override
+        public void callSessionTerminated(IImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+            if (mListener != null) {
+                mListener.callSessionTerminated(ImsCallSession.this, reasonInfo);
+            }
+        }
+
+        /**
+         * Notifies the result of the call hold/resume operation.
+         */
+        @Override
+        public void callSessionHeld(IImsCallSession session,
+                ImsCallProfile profile) {
+            if (mListener != null) {
+                mListener.callSessionHeld(ImsCallSession.this, profile);
+            }
+        }
+
+        @Override
+        public void callSessionHoldFailed(IImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+            if (mListener != null) {
+                mListener.callSessionHoldFailed(ImsCallSession.this, reasonInfo);
+            }
+        }
+
+        @Override
+        public void callSessionHoldReceived(IImsCallSession session,
+                ImsCallProfile profile) {
+            if (mListener != null) {
+                mListener.callSessionHoldReceived(ImsCallSession.this, profile);
+            }
+        }
+
+        @Override
+        public void callSessionResumed(IImsCallSession session,
+                ImsCallProfile profile) {
+            if (mListener != null) {
+                mListener.callSessionResumed(ImsCallSession.this, profile);
+            }
+        }
+
+        @Override
+        public void callSessionResumeFailed(IImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+            if (mListener != null) {
+                mListener.callSessionResumeFailed(ImsCallSession.this, reasonInfo);
+            }
+        }
+
+        @Override
+        public void callSessionResumeReceived(IImsCallSession session,
+                ImsCallProfile profile) {
+            if (mListener != null) {
+                mListener.callSessionResumeReceived(ImsCallSession.this, profile);
+            }
+        }
+
+        /**
+         * Notifies the start of a call merge operation.
+         *
+         * @param session The call session.
+         * @param newSession The merged call session.
+         * @param profile The call profile.
+         */
+        @Override
+        public void callSessionMergeStarted(IImsCallSession session,
+                IImsCallSession newSession, ImsCallProfile profile) {
+            // This callback can be used for future use to add additional
+            // functionality that may be needed between conference start and complete
+            Log.d(TAG, "callSessionMergeStarted");
+        }
+
+        /**
+         * Notifies the successful completion of a call merge operation.
+         *
+         * @param newSession The call session.
+         */
+        @Override
+        public void callSessionMergeComplete(IImsCallSession newSession) {
+            if (mListener != null) {
+                if (newSession != null) {
+                    // Check if the active session is the same session that was
+                    // active before the merge request was sent.
+                    ImsCallSession validActiveSession = ImsCallSession.this;
+                    try {
+                        if (!Objects.equals(miSession.getCallId(), newSession.getCallId())) {
+                            // New session created after conference
+                            validActiveSession = new ImsCallSession(newSession);
+                        }
+                    } catch (RemoteException rex) {
+                        Log.e(TAG, "callSessionMergeComplete: exception for getCallId!");
+                    }
+                    mListener.callSessionMergeComplete(validActiveSession);
+               } else {
+                   // Session already exists. Hence no need to pass
+                   mListener.callSessionMergeComplete(null);
+               }
+            }
+        }
+
+        /**
+         * Notifies of a failure to perform a call merge operation.
+         *
+         * @param session The call session.
+         * @param reasonInfo The merge failure reason.
+         */
+        @Override
+        public void callSessionMergeFailed(IImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+            if (mListener != null) {
+                mListener.callSessionMergeFailed(ImsCallSession.this, reasonInfo);
+            }
+        }
+
+        /**
+         * Notifies the result of call upgrade / downgrade or any other call updates.
+         */
+        @Override
+        public void callSessionUpdated(IImsCallSession session,
+                ImsCallProfile profile) {
+            if (mListener != null) {
+                mListener.callSessionUpdated(ImsCallSession.this, profile);
+            }
+        }
+
+        @Override
+        public void callSessionUpdateFailed(IImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+            if (mListener != null) {
+                mListener.callSessionUpdateFailed(ImsCallSession.this, reasonInfo);
+            }
+        }
+
+        @Override
+        public void callSessionUpdateReceived(IImsCallSession session,
+                ImsCallProfile profile) {
+            if (mListener != null) {
+                mListener.callSessionUpdateReceived(ImsCallSession.this, profile);
+            }
+        }
+
+        /**
+         * Notifies the result of conference extension.
+         */
+        @Override
+        public void callSessionConferenceExtended(IImsCallSession session,
+                IImsCallSession newSession, ImsCallProfile profile) {
+            if (mListener != null) {
+                mListener.callSessionConferenceExtended(ImsCallSession.this,
+                        new ImsCallSession(newSession), profile);
+            }
+        }
+
+        @Override
+        public void callSessionConferenceExtendFailed(IImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+            if (mListener != null) {
+                mListener.callSessionConferenceExtendFailed(ImsCallSession.this, reasonInfo);
+            }
+        }
+
+        @Override
+        public void callSessionConferenceExtendReceived(IImsCallSession session,
+                IImsCallSession newSession, ImsCallProfile profile) {
+            if (mListener != null) {
+                mListener.callSessionConferenceExtendReceived(ImsCallSession.this,
+                        new ImsCallSession(newSession), profile);
+            }
+        }
+
+        /**
+         * Notifies the result of the participant invitation / removal to/from
+         * the conference session.
+         */
+        @Override
+        public void callSessionInviteParticipantsRequestDelivered(IImsCallSession session) {
+            if (mListener != null) {
+                mListener.callSessionInviteParticipantsRequestDelivered(ImsCallSession.this);
+            }
+        }
+
+        @Override
+        public void callSessionInviteParticipantsRequestFailed(IImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+            if (mListener != null) {
+                mListener.callSessionInviteParticipantsRequestFailed(ImsCallSession.this,
+                        reasonInfo);
+            }
+        }
+
+        @Override
+        public void callSessionRemoveParticipantsRequestDelivered(IImsCallSession session) {
+            if (mListener != null) {
+                mListener.callSessionRemoveParticipantsRequestDelivered(ImsCallSession.this);
+            }
+        }
+
+        @Override
+        public void callSessionRemoveParticipantsRequestFailed(IImsCallSession session,
+                ImsReasonInfo reasonInfo) {
+            if (mListener != null) {
+                mListener.callSessionRemoveParticipantsRequestFailed(ImsCallSession.this,
+                        reasonInfo);
+            }
+        }
+
+        /**
+         * Notifies the changes of the conference info. in the conference session.
+         */
+        @Override
+        public void callSessionConferenceStateUpdated(IImsCallSession session,
+                ImsConferenceState state) {
+            if (mListener != null) {
+                mListener.callSessionConferenceStateUpdated(ImsCallSession.this, state);
+            }
+        }
+
+        /**
+         * Notifies the incoming USSD message.
+         */
+        @Override
+        public void callSessionUssdMessageReceived(IImsCallSession session,
+                int mode, String ussdMessage) {
+            if (mListener != null) {
+                mListener.callSessionUssdMessageReceived(ImsCallSession.this, mode, ussdMessage);
+            }
+        }
+
+        /**
+         * Notifies of handover information for this call
+         */
+        @Override
+        public void callSessionHandover(IImsCallSession session,
+                                 int srcAccessTech, int targetAccessTech,
+                                 ImsReasonInfo reasonInfo) {
+            if (mListener != null) {
+                mListener.callSessionHandover(ImsCallSession.this, srcAccessTech,
+                        targetAccessTech, reasonInfo);
+            }
+        }
+
+        /**
+         * Notifies of handover failure info for this call
+         */
+        @Override
+        public void callSessionHandoverFailed(IImsCallSession session,
+                                       int srcAccessTech, int targetAccessTech,
+                                       ImsReasonInfo reasonInfo) {
+            if (mListener != null) {
+                mListener.callSessionHandoverFailed(ImsCallSession.this, srcAccessTech,
+                        targetAccessTech, reasonInfo);
+            }
+        }
+
+        /**
+         * Notifies the TTY mode received from remote party.
+         */
+        @Override
+        public void callSessionTtyModeReceived(IImsCallSession session,
+                int mode) {
+            if (mListener != null) {
+                mListener.callSessionTtyModeReceived(ImsCallSession.this, mode);
+            }
+        }
+
+        /**
+         * Notifies of a change to the multiparty state for this {@code ImsCallSession}.
+         *
+         * @param session The call session.
+         * @param isMultiParty {@code true} if the session became multiparty, {@code false}
+         *      otherwise.
+         */
+        public void callSessionMultipartyStateChanged(IImsCallSession session,
+                boolean isMultiParty) {
+
+            if (mListener != null) {
+                mListener.callSessionMultipartyStateChanged(ImsCallSession.this, isMultiParty);
+            }
+        }
+
+        @Override
+        public void callSessionSuppServiceReceived(IImsCallSession session,
+                ImsSuppServiceNotification suppServiceInfo ) {
+            if (mListener != null) {
+                mListener.callSessionSuppServiceReceived(ImsCallSession.this, suppServiceInfo);
+            }
+        }
+
+    }
+
+    /**
+     * Provides a string representation of the {@link ImsCallSession}.  Primarily intended for
+     * use in log statements.
+     *
+     * @return String representation of session.
+     */
+    @Override
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+        sb.append("[ImsCallSession objId:");
+        sb.append(System.identityHashCode(this));
+        sb.append(" state:");
+        sb.append(State.toString(getState()));
+        sb.append(" callId:");
+        sb.append(getCallId());
+        sb.append("]");
+        return sb.toString();
+    }
+}
diff --git a/telephony/java/com/android/ims/internal/ImsVideoCallProvider.java b/telephony/java/com/android/ims/internal/ImsVideoCallProvider.java
new file mode 100644
index 0000000..432dc39
--- /dev/null
+++ b/telephony/java/com/android/ims/internal/ImsVideoCallProvider.java
@@ -0,0 +1,294 @@
+/*
+ * 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.ims.internal;
+
+import android.net.Uri;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
+import android.os.RemoteException;
+import android.telecom.Connection;
+import android.telecom.VideoProfile;
+import android.telecom.VideoProfile.CameraCapabilities;
+import android.view.Surface;
+
+import com.android.internal.os.SomeArgs;
+
+/**
+ * @hide
+ */
+public abstract class ImsVideoCallProvider {
+    private static final int MSG_SET_CALLBACK = 1;
+    private static final int MSG_SET_CAMERA = 2;
+    private static final int MSG_SET_PREVIEW_SURFACE = 3;
+    private static final int MSG_SET_DISPLAY_SURFACE = 4;
+    private static final int MSG_SET_DEVICE_ORIENTATION = 5;
+    private static final int MSG_SET_ZOOM = 6;
+    private static final int MSG_SEND_SESSION_MODIFY_REQUEST = 7;
+    private static final int MSG_SEND_SESSION_MODIFY_RESPONSE = 8;
+    private static final int MSG_REQUEST_CAMERA_CAPABILITIES = 9;
+    private static final int MSG_REQUEST_CALL_DATA_USAGE = 10;
+    private static final int MSG_SET_PAUSE_IMAGE = 11;
+
+    private final ImsVideoCallProviderBinder mBinder;
+
+    private IImsVideoCallCallback mCallback;
+
+    /**
+     * Default handler used to consolidate binder method calls onto a single thread.
+     */
+    private final Handler mProviderHandler = new Handler(Looper.getMainLooper()) {
+        @Override
+        public void handleMessage(Message msg) {
+            switch (msg.what) {
+                case MSG_SET_CALLBACK:
+                    mCallback = (IImsVideoCallCallback) msg.obj;
+                    break;
+                case MSG_SET_CAMERA:
+                {
+                    SomeArgs args = (SomeArgs) msg.obj;
+                    try {
+                        onSetCamera((String) args.arg1);
+                        onSetCamera((String) args.arg1, args.argi1);
+                    } finally {
+                        args.recycle();
+                    }
+                    break;
+                }
+                case MSG_SET_PREVIEW_SURFACE:
+                    onSetPreviewSurface((Surface) msg.obj);
+                    break;
+                case MSG_SET_DISPLAY_SURFACE:
+                    onSetDisplaySurface((Surface) msg.obj);
+                    break;
+                case MSG_SET_DEVICE_ORIENTATION:
+                    onSetDeviceOrientation(msg.arg1);
+                    break;
+                case MSG_SET_ZOOM:
+                    onSetZoom((Float) msg.obj);
+                    break;
+                case MSG_SEND_SESSION_MODIFY_REQUEST: {
+                    SomeArgs args = (SomeArgs) msg.obj;
+                    try {
+                        VideoProfile fromProfile = (VideoProfile) args.arg1;
+                        VideoProfile toProfile = (VideoProfile) args.arg2;
+
+                        onSendSessionModifyRequest(fromProfile, toProfile);
+                    } finally {
+                        args.recycle();
+                    }
+                    break;
+                }
+                case MSG_SEND_SESSION_MODIFY_RESPONSE:
+                    onSendSessionModifyResponse((VideoProfile) msg.obj);
+                    break;
+                case MSG_REQUEST_CAMERA_CAPABILITIES:
+                    onRequestCameraCapabilities();
+                    break;
+                case MSG_REQUEST_CALL_DATA_USAGE:
+                    onRequestCallDataUsage();
+                    break;
+                case MSG_SET_PAUSE_IMAGE:
+                    onSetPauseImage((Uri) msg.obj);
+                    break;
+                default:
+                    break;
+            }
+        }
+    };
+
+    /**
+     * IImsVideoCallProvider stub implementation.
+     */
+    private final class ImsVideoCallProviderBinder extends IImsVideoCallProvider.Stub {
+        public void setCallback(IImsVideoCallCallback callback) {
+            mProviderHandler.obtainMessage(MSG_SET_CALLBACK, callback).sendToTarget();
+        }
+
+        public void setCamera(String cameraId, int uid) {
+            SomeArgs args = SomeArgs.obtain();
+            args.arg1 = cameraId;
+            args.argi1 = uid;
+            mProviderHandler.obtainMessage(MSG_SET_CAMERA, args).sendToTarget();
+        }
+
+        public void setPreviewSurface(Surface surface) {
+            mProviderHandler.obtainMessage(MSG_SET_PREVIEW_SURFACE, surface).sendToTarget();
+        }
+
+        public void setDisplaySurface(Surface surface) {
+            mProviderHandler.obtainMessage(MSG_SET_DISPLAY_SURFACE, surface).sendToTarget();
+        }
+
+        public void setDeviceOrientation(int rotation) {
+            mProviderHandler.obtainMessage(MSG_SET_DEVICE_ORIENTATION, rotation, 0).sendToTarget();
+        }
+
+        public void setZoom(float value) {
+            mProviderHandler.obtainMessage(MSG_SET_ZOOM, value).sendToTarget();
+        }
+
+        public void sendSessionModifyRequest(VideoProfile fromProfile, VideoProfile toProfile) {
+            SomeArgs args = SomeArgs.obtain();
+            args.arg1 = fromProfile;
+            args.arg2 = toProfile;
+            mProviderHandler.obtainMessage(MSG_SEND_SESSION_MODIFY_REQUEST, args).sendToTarget();
+        }
+
+        public void sendSessionModifyResponse(VideoProfile responseProfile) {
+            mProviderHandler.obtainMessage(
+                    MSG_SEND_SESSION_MODIFY_RESPONSE, responseProfile).sendToTarget();
+        }
+
+        public void requestCameraCapabilities() {
+            mProviderHandler.obtainMessage(MSG_REQUEST_CAMERA_CAPABILITIES).sendToTarget();
+        }
+
+        public void requestCallDataUsage() {
+            mProviderHandler.obtainMessage(MSG_REQUEST_CALL_DATA_USAGE).sendToTarget();
+        }
+
+        public void setPauseImage(Uri uri) {
+            mProviderHandler.obtainMessage(MSG_SET_PAUSE_IMAGE, uri).sendToTarget();
+        }
+    }
+
+    public ImsVideoCallProvider() {
+        mBinder = new ImsVideoCallProviderBinder();
+    }
+
+    /**
+     * Returns binder object which can be used across IPC methods.
+     */
+    public final IImsVideoCallProvider getInterface() {
+        return mBinder;
+    }
+
+    /** @see Connection.VideoProvider#onSetCamera */
+    public abstract void onSetCamera(String cameraId);
+
+    /**
+     * Similar to {@link #onSetCamera(String)}, except includes the UID of the calling process which
+     * the IMS service uses when opening the camera.  This ensures camera permissions are verified
+     * by the camera service.
+     *
+     * @param cameraId The id of the camera to be opened.
+     * @param uid The uid of the caller, used when opening the camera for permission verification.
+     * @see Connection.VideoProvider#onSetCamera
+     */
+    public void onSetCamera(String cameraId, int uid) {
+    }
+
+    /** @see Connection.VideoProvider#onSetPreviewSurface */
+    public abstract void onSetPreviewSurface(Surface surface);
+
+    /** @see Connection.VideoProvider#onSetDisplaySurface */
+    public abstract void onSetDisplaySurface(Surface surface);
+
+    /** @see Connection.VideoProvider#onSetDeviceOrientation */
+    public abstract void onSetDeviceOrientation(int rotation);
+
+    /** @see Connection.VideoProvider#onSetZoom */
+    public abstract void onSetZoom(float value);
+
+    /** @see Connection.VideoProvider#onSendSessionModifyRequest */
+    public abstract void onSendSessionModifyRequest(VideoProfile fromProfile,
+            VideoProfile toProfile);
+
+    /** @see Connection.VideoProvider#onSendSessionModifyResponse */
+    public abstract void onSendSessionModifyResponse(VideoProfile responseProfile);
+
+    /** @see Connection.VideoProvider#onRequestCameraCapabilities */
+    public abstract void onRequestCameraCapabilities();
+
+    /** @see Connection.VideoProvider#onRequestCallDataUsage */
+    public abstract void onRequestCallDataUsage();
+
+    /** @see Connection.VideoProvider#onSetPauseImage */
+    public abstract void onSetPauseImage(Uri uri);
+
+    /** @see Connection.VideoProvider#receiveSessionModifyRequest */
+    public void receiveSessionModifyRequest(VideoProfile VideoProfile) {
+        if (mCallback != null) {
+            try {
+                mCallback.receiveSessionModifyRequest(VideoProfile);
+            } catch (RemoteException ignored) {
+            }
+        }
+    }
+
+    /** @see Connection.VideoProvider#receiveSessionModifyResponse */
+    public void receiveSessionModifyResponse(
+            int status, VideoProfile requestedProfile, VideoProfile responseProfile) {
+        if (mCallback != null) {
+            try {
+                mCallback.receiveSessionModifyResponse(status, requestedProfile, responseProfile);
+            } catch (RemoteException ignored) {
+            }
+        }
+    }
+
+    /** @see Connection.VideoProvider#handleCallSessionEvent */
+    public void handleCallSessionEvent(int event) {
+        if (mCallback != null) {
+            try {
+                mCallback.handleCallSessionEvent(event);
+            } catch (RemoteException ignored) {
+            }
+        }
+    }
+
+    /** @see Connection.VideoProvider#changePeerDimensions */
+    public void changePeerDimensions(int width, int height) {
+        if (mCallback != null) {
+            try {
+                mCallback.changePeerDimensions(width, height);
+            } catch (RemoteException ignored) {
+            }
+        }
+    }
+
+    /** @see Connection.VideoProvider#changeCallDataUsage */
+    public void changeCallDataUsage(long dataUsage) {
+        if (mCallback != null) {
+            try {
+                mCallback.changeCallDataUsage(dataUsage);
+            } catch (RemoteException ignored) {
+            }
+        }
+    }
+
+    /** @see Connection.VideoProvider#changeCameraCapabilities */
+    public void changeCameraCapabilities(CameraCapabilities CameraCapabilities) {
+        if (mCallback != null) {
+            try {
+                mCallback.changeCameraCapabilities(CameraCapabilities);
+            } catch (RemoteException ignored) {
+            }
+        }
+    }
+
+    /** @see Connection.VideoProvider#changeVideoQuality */
+    public void changeVideoQuality(int videoQuality) {
+        if (mCallback != null) {
+            try {
+                mCallback.changeVideoQuality(videoQuality);
+            } catch (RemoteException ignored) {
+            }
+        }
+    }
+}
diff --git a/telephony/java/com/android/internal/telephony/TelephonyIntents.java b/telephony/java/com/android/internal/telephony/TelephonyIntents.java
index 7fd511f..d40835b 100644
--- a/telephony/java/com/android/internal/telephony/TelephonyIntents.java
+++ b/telephony/java/com/android/internal/telephony/TelephonyIntents.java
@@ -411,7 +411,7 @@
      * <p class="note">This is a protected intent that can only be sent by the system.</p>
      */
     public static final String ACTION_CARRIER_SIGNAL_REDIRECTED =
-            "android.intent.action.CARRIER_SIGNAL_REDIRECTED";
+            "com.android.internal.telephony.CARRIER_SIGNAL_REDIRECTED";
     /**
      * <p>Broadcast Action: when data connections setup fails.
      * intended for sim/account status checks and only sent to the specified carrier app
@@ -424,7 +424,7 @@
      * <p class="note">This is a protected intent that can only be sent by the system. </p>
      */
     public static final String ACTION_CARRIER_SIGNAL_REQUEST_NETWORK_FAILED =
-            "android.intent.action.CARRIER_SIGNAL_REQUEST_NETWORK_FAILED";
+            "com.android.internal.telephony.CARRIER_SIGNAL_REQUEST_NETWORK_FAILED";
 
     /**
      * <p>Broadcast Action: when pco value is available.
@@ -441,7 +441,7 @@
      * <p class="note">This is a protected intent that can only be sent by the system. </p>
      */
     public static final String ACTION_CARRIER_SIGNAL_PCO_VALUE =
-            "android.intent.action.CARRIER_SIGNAL_PCO_VALUE";
+            "com.android.internal.telephony.CARRIER_SIGNAL_PCO_VALUE";
 
     // CARRIER_SIGNAL_ACTION extra keys
     public static final String EXTRA_REDIRECTION_URL_KEY = "redirectionUrl";
diff --git a/test-runner/src/android/test/suitebuilder/TestMethod.java b/test-runner/src/android/test/suitebuilder/TestMethod.java
index 08568d5..ae1db5e 100644
--- a/test-runner/src/android/test/suitebuilder/TestMethod.java
+++ b/test-runner/src/android/test/suitebuilder/TestMethod.java
@@ -26,7 +26,11 @@
 /**
  * Represents a test to be run. Can be constructed without instantiating the TestCase or even
  * loading the class.
+ *
+ * @deprecated New tests should be written using the
+ * <a href="{@docRoot}tools/testing-support-library/index.html">Android Testing Support Library</a>.
  */
+@Deprecated
 public class TestMethod {
 
     private final String enclosingClassname;
diff --git a/test-runner/src/android/test/suitebuilder/TestSuiteBuilder.java b/test-runner/src/android/test/suitebuilder/TestSuiteBuilder.java
index 8c89489..3b920cf 100644
--- a/test-runner/src/android/test/suitebuilder/TestSuiteBuilder.java
+++ b/test-runner/src/android/test/suitebuilder/TestSuiteBuilder.java
@@ -38,7 +38,11 @@
 /**
  * Build suites based on a combination of included packages, excluded packages,
  * and predicates that must be satisfied.
+ *
+ * @deprecated New tests should be written using the
+ * <a href="{@docRoot}tools/testing-support-library/index.html">Android Testing Support Library</a>.
  */
+@Deprecated
 public class TestSuiteBuilder {
 
     private Context context;
@@ -223,7 +227,11 @@
     /**
      * A special {@link junit.framework.TestCase} used to indicate a failure during the build()
      * step.
+     *
+     * @deprecated New tests should be written using the
+     * <a href="{@docRoot}tools/testing-support-library/index.html">Android Testing Support Library</a>.
      */
+    @Deprecated
     public static class FailedToCreateTests extends TestCase {
         private final Exception exception;
 
diff --git a/tests/SharedLibrary/client/Android.mk b/tests/SharedLibrary/client/Android.mk
index 1d66bb9..a04fb05 100644
--- a/tests/SharedLibrary/client/Android.mk
+++ b/tests/SharedLibrary/client/Android.mk
@@ -1,6 +1,7 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
 
+LOCAL_USE_AAPT2 := true
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 
 LOCAL_RES_LIBRARIES := SharedLibrary
diff --git a/tests/SharedLibrary/lib/Android.mk b/tests/SharedLibrary/lib/Android.mk
index b2fc369..78fcb8b 100644
--- a/tests/SharedLibrary/lib/Android.mk
+++ b/tests/SharedLibrary/lib/Android.mk
@@ -1,5 +1,6 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
+LOCAL_USE_AAPT2 := true
 
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 
diff --git a/tests/SharedLibrary/lib/res/values/public.xml b/tests/SharedLibrary/lib/res/values/public.xml
index 23d307e..8d7a7ad 100644
--- a/tests/SharedLibrary/lib/res/values/public.xml
+++ b/tests/SharedLibrary/lib/res/values/public.xml
@@ -15,5 +15,5 @@
 
     <public type="drawable" name="size_48x48" id="0x00030000" />
 
-    <public type="array" name="animals"     id="0x02050000" />
+    <public type="array" name="animals"     id="0x00050000" />
 </resources>
diff --git a/tests/net/java/com/android/server/connectivity/MetricsTestUtil.java b/tests/net/java/com/android/server/connectivity/MetricsTestUtil.java
index e201012..c5965e8 100644
--- a/tests/net/java/com/android/server/connectivity/MetricsTestUtil.java
+++ b/tests/net/java/com/android/server/connectivity/MetricsTestUtil.java
@@ -17,101 +17,59 @@
 package com.android.server.connectivity;
 
 import android.net.ConnectivityMetricsEvent;
-import android.net.ConnectivityMetricsLogger;
 import android.os.Bundle;
 import android.os.Parcel;
 import android.os.Parcelable;
 
+import java.util.function.Consumer;
+
 abstract public class MetricsTestUtil {
     private MetricsTestUtil() {
     }
 
-    static ConnectivityMetricsEvent ipEv(Parcelable p) {
-        return ev(ConnectivityMetricsLogger.COMPONENT_TAG_CONNECTIVITY, p);
+    static ConnectivityMetricsEvent ev(Parcelable p) {
+        return new ConnectivityMetricsEvent(1L, 0, 0, p);
     }
 
-    static ConnectivityMetricsEvent telephonyEv() {
-        return ev(ConnectivityMetricsLogger.COMPONENT_TAG_TELEPHONY, new Bundle());
-    }
-
-    static ConnectivityMetricsEvent ev(int tag, Parcelable p) {
-        return new ConnectivityMetricsEvent(1L, tag, 0, p);
-    }
-
-    // Utiliy interface for describing the content of a Parcel. This relies on
-    // the implementation defails of Parcelable and on the fact that the fully
-    // qualified Parcelable class names are written as string in the Parcels.
-    interface ParcelField {
-        void write(Parcel p);
-    }
-
-    static ConnectivityMetricsEvent describeIpEvent(ParcelField... fs) {
+    static ConnectivityMetricsEvent describeIpEvent(Consumer<Parcel>... fs) {
         Parcel p = Parcel.obtain();
-        for (ParcelField f : fs) {
-            f.write(p);
+        for (Consumer<Parcel> f : fs) {
+            f.accept(p);
         }
         p.setDataPosition(0);
-        return ipEv(p.readParcelable(ClassLoader.getSystemClassLoader()));
+        return ev(p.readParcelable(ClassLoader.getSystemClassLoader()));
     }
 
-    static ParcelField aType(Class<?> c) {
-        return new ParcelField() {
-            public void write(Parcel p) {
-                p.writeString(c.getName());
-            }
-        };
+    static Consumer<Parcel> aType(Class<?> c) {
+        return aString(c.getName());
     }
 
-    static ParcelField aBool(boolean b) {
+    static Consumer<Parcel> aBool(boolean b) {
         return aByte((byte) (b ? 1 : 0));
     }
 
-    static ParcelField aByte(byte b) {
-        return new ParcelField() {
-            public void write(Parcel p) {
-                p.writeByte(b);
-            }
-        };
+    static Consumer<Parcel> aByte(byte b) {
+        return (p) -> p.writeByte(b);
     }
 
-    static ParcelField anInt(int i) {
-        return new ParcelField() {
-            public void write(Parcel p) {
-                p.writeInt(i);
-            }
-        };
+    static Consumer<Parcel> anInt(int i) {
+        return (p) -> p.writeInt(i);
     }
 
-    static ParcelField aLong(long l) {
-        return new ParcelField() {
-            public void write(Parcel p) {
-                p.writeLong(l);
-            }
-        };
+    static Consumer<Parcel> aLong(long l) {
+        return (p) -> p.writeLong(l);
     }
 
-    static ParcelField aString(String s) {
-        return new ParcelField() {
-            public void write(Parcel p) {
-                p.writeString(s);
-            }
-        };
+    static Consumer<Parcel> aString(String s) {
+        return (p) -> p.writeString(s);
     }
 
-    static ParcelField aByteArray(byte... ary) {
-        return new ParcelField() {
-            public void write(Parcel p) {
-                p.writeByteArray(ary);
-            }
-        };
+    static Consumer<Parcel> aByteArray(byte... ary) {
+        return (p) -> p.writeByteArray(ary);
     }
 
-    static ParcelField anIntArray(int... ary) {
-        return new ParcelField() {
-            public void write(Parcel p) {
-                p.writeIntArray(ary);
-            }
-        };
+    static Consumer<Parcel> anIntArray(int... ary) {
+        return (p) -> p.writeIntArray(ary);
     }
 
     static byte b(int i) {
diff --git a/tools/aapt2/Android.bp b/tools/aapt2/Android.bp
index dabaca6..57036aa 100644
--- a/tools/aapt2/Android.bp
+++ b/tools/aapt2/Android.bp
@@ -1,5 +1,5 @@
 //
-// Copyright (C) 2015 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.
@@ -19,7 +19,7 @@
     "diff/Diff.cpp",
     "dump/Dump.cpp",
     "link/Link.cpp",
-    "strip/Strip.cpp",
+    "optimize/Optimize.cpp",
 ]
 
 cc_defaults {
@@ -96,11 +96,11 @@
         "link/ProductFilter.cpp",
         "link/PrivateAttributeMover.cpp",
         "link/ReferenceLinker.cpp",
-        "link/ResourceDeduper.cpp",
         "link/TableMerger.cpp",
-        "link/VersionCollapser.cpp",
         "link/XmlNamespaceRemover.cpp",
         "link/XmlReferenceLinker.cpp",
+        "optimize/ResourceDeduper.cpp",
+        "optimize/VersionCollapser.cpp",
         "process/SymbolTable.cpp",
         "proto/ProtoHelpers.cpp",
         "proto/TableProtoDeserializer.cpp",
diff --git a/tools/aapt2/LoadedApk.cpp b/tools/aapt2/LoadedApk.cpp
index 407550b..1d04b35 100644
--- a/tools/aapt2/LoadedApk.cpp
+++ b/tools/aapt2/LoadedApk.cpp
@@ -58,7 +58,8 @@
   return util::make_unique<LoadedApk>(source, std::move(apk), std::move(table));
 }
 
-bool LoadedApk::WriteToArchive(IAaptContext* context, IArchiveWriter* writer) {
+bool LoadedApk::WriteToArchive(IAaptContext* context, const TableFlattenerOptions& options,
+                               IArchiveWriter* writer) {
   std::set<std::string> referenced_resources;
   // List the files being referenced in the resource table.
   for (auto& pkg : table_->packages) {
@@ -96,7 +97,7 @@
       BigBuffer buffer = BigBuffer(1024);
       // TODO(adamlesinski): How to determine if there were sparse entries (and if to encode
       // with sparse entries) b/35389232.
-      TableFlattener flattener({}, &buffer);
+      TableFlattener flattener(options, &buffer);
       if (!flattener.Consume(context, table_.get())) {
         return false;
       }
diff --git a/tools/aapt2/LoadedApk.h b/tools/aapt2/LoadedApk.h
index f8878d1..59eb816 100644
--- a/tools/aapt2/LoadedApk.h
+++ b/tools/aapt2/LoadedApk.h
@@ -21,6 +21,7 @@
 
 #include "ResourceTable.h"
 #include "flatten/Archive.h"
+#include "flatten/TableFlattener.h"
 #include "io/ZipArchive.h"
 #include "unflatten/BinaryResourceParser.h"
 
@@ -45,7 +46,8 @@
    * Writes the APK on disk at the given path, while also removing the resource
    * files that are not referenced in the resource table.
    */
-  bool WriteToArchive(IAaptContext* context, IArchiveWriter* writer);
+  bool WriteToArchive(IAaptContext* context, const TableFlattenerOptions& options,
+                      IArchiveWriter* writer);
 
   static std::unique_ptr<LoadedApk> LoadApkFromPath(IAaptContext* context,
                                                     const android::StringPiece& path);
diff --git a/tools/aapt2/Main.cpp b/tools/aapt2/Main.cpp
index ba378d7..38d9ef8 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 = "7";
+static const char* sMinorVersion = "9";
 
 int PrintVersion() {
   std::cerr << "Android Asset Packaging Tool (aapt) " << sMajorVersion << "."
@@ -37,7 +37,7 @@
 extern int Link(const std::vector<android::StringPiece>& args);
 extern int Dump(const std::vector<android::StringPiece>& args);
 extern int Diff(const std::vector<android::StringPiece>& args);
-extern int Strip(const std::vector<android::StringPiece>& args);
+extern int Optimize(const std::vector<android::StringPiece>& args);
 
 }  // namespace aapt
 
@@ -60,8 +60,8 @@
       return aapt::Dump(args);
     } else if (command == "diff") {
       return aapt::Diff(args);
-    } else if (command == "strip") {
-      return aapt::Strip(args);
+    } else if (command == "optimize") {
+      return aapt::Optimize(args);
     } else if (command == "version") {
       return aapt::PrintVersion();
     }
@@ -70,7 +70,7 @@
     std::cerr << "no command specified\n";
   }
 
-  std::cerr << "\nusage: aapt2 [compile|link|dump|diff|strip|version] ..."
+  std::cerr << "\nusage: aapt2 [compile|link|dump|diff|optimize|version] ..."
             << std::endl;
   return 1;
 }
diff --git a/tools/aapt2/NameMangler.h b/tools/aapt2/NameMangler.h
index dba2d09..1305a4c 100644
--- a/tools/aapt2/NameMangler.h
+++ b/tools/aapt2/NameMangler.h
@@ -62,6 +62,8 @@
     return policy_.packages_to_mangle.count(package) != 0;
   }
 
+  const std::string& GetTargetPackageName() const { return policy_.target_package_name; }
+
   /**
    * Returns a mangled name that is a combination of `name` and `package`.
    * The mangled name should contain symbols that are illegal to define in XML,
diff --git a/tools/aapt2/Resource.h b/tools/aapt2/Resource.h
index 4d915d9..493f238 100644
--- a/tools/aapt2/Resource.h
+++ b/tools/aapt2/Resource.h
@@ -118,6 +118,9 @@
   bool is_valid() const;
 };
 
+constexpr const uint8_t kAppPackageId = 0x7fu;
+constexpr const uint8_t kFrameworkPackageId = 0x01u;
+
 /**
  * A binary identifier representing a resource. Internally it
  * is a 32bit integer split as follows:
@@ -138,6 +141,10 @@
   ResourceId(uint8_t p, uint8_t t, uint16_t e);
 
   bool is_valid() const;
+
+  // Returns true if the ID is a valid ID or dynamic ID (package ID can be 0).
+  bool is_valid_dynamic() const;
+
   uint8_t package_id() const;
   uint8_t type_id() const;
   uint16_t entry_id() const;
@@ -211,6 +218,8 @@
   return (id & 0xff000000u) != 0 && (id & 0x00ff0000u) != 0;
 }
 
+inline bool ResourceId::is_valid_dynamic() const { return (id & 0x00ff0000u) != 0; }
+
 inline uint8_t ResourceId::package_id() const {
   return static_cast<uint8_t>(id >> 24);
 }
diff --git a/tools/aapt2/ResourceParser.cpp b/tools/aapt2/ResourceParser.cpp
index 47ca266..8461905 100644
--- a/tools/aapt2/ResourceParser.cpp
+++ b/tools/aapt2/ResourceParser.cpp
@@ -701,14 +701,11 @@
 
   out_resource->name.type = *parsed_type;
 
-  if (Maybe<StringPiece> maybe_id_str =
-          xml::FindNonEmptyAttribute(parser, "id")) {
-    Maybe<ResourceId> maybe_id =
-        ResourceUtils::ParseResourceId(maybe_id_str.value());
+  if (Maybe<StringPiece> maybe_id_str = xml::FindNonEmptyAttribute(parser, "id")) {
+    Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(maybe_id_str.value());
     if (!maybe_id) {
-      diag_->Error(DiagMessage(out_resource->source) << "invalid resource ID '"
-                                                     << maybe_id.value()
-                                                     << "' in <public>");
+      diag_->Error(DiagMessage(out_resource->source)
+                   << "invalid resource ID '" << maybe_id_str.value() << "' in <public>");
       return false;
     }
     out_resource->id = maybe_id.value();
diff --git a/tools/aapt2/ResourceTable.cpp b/tools/aapt2/ResourceTable.cpp
index dd78750..6e4b450 100644
--- a/tools/aapt2/ResourceTable.cpp
+++ b/tools/aapt2/ResourceTable.cpp
@@ -387,8 +387,7 @@
   }
 
   ResourceTablePackage* package = FindOrCreatePackage(name.package);
-  if (res_id.is_valid() && package->id &&
-      package->id.value() != res_id.package_id()) {
+  if (res_id.is_valid_dynamic() && package->id && package->id.value() != res_id.package_id()) {
     diag->Error(DiagMessage(value->GetSource())
                 << "trying to add resource '" << name << "' with ID " << res_id
                 << " but package '" << package->name << "' already has ID "
@@ -397,7 +396,7 @@
   }
 
   ResourceTableType* type = package->FindOrCreateType(name.type);
-  if (res_id.is_valid() && type->id && type->id.value() != res_id.type_id()) {
+  if (res_id.is_valid_dynamic() && type->id && type->id.value() != res_id.type_id()) {
     diag->Error(DiagMessage(value->GetSource())
                 << "trying to add resource '" << name << "' with ID " << res_id
                 << " but type '" << type->type << "' already has ID "
@@ -406,8 +405,7 @@
   }
 
   ResourceEntry* entry = type->FindOrCreateEntry(name.entry);
-  if (res_id.is_valid() && entry->id &&
-      entry->id.value() != res_id.entry_id()) {
+  if (res_id.is_valid_dynamic() && entry->id && entry->id.value() != res_id.entry_id()) {
     diag->Error(DiagMessage(value->GetSource())
                 << "trying to add resource '" << name << "' with ID " << res_id
                 << " but resource already has ID "
@@ -441,7 +439,7 @@
     }
   }
 
-  if (res_id.is_valid()) {
+  if (res_id.is_valid_dynamic()) {
     package->id = res_id.package_id();
     type->id = res_id.type_id();
     entry->id = res_id.entry_id();
@@ -480,8 +478,7 @@
   }
 
   ResourceTablePackage* package = FindOrCreatePackage(name.package);
-  if (res_id.is_valid() && package->id &&
-      package->id.value() != res_id.package_id()) {
+  if (res_id.is_valid_dynamic() && package->id && package->id.value() != res_id.package_id()) {
     diag->Error(DiagMessage(symbol.source)
                 << "trying to add resource '" << name << "' with ID " << res_id
                 << " but package '" << package->name << "' already has ID "
@@ -490,7 +487,7 @@
   }
 
   ResourceTableType* type = package->FindOrCreateType(name.type);
-  if (res_id.is_valid() && type->id && type->id.value() != res_id.type_id()) {
+  if (res_id.is_valid_dynamic() && type->id && type->id.value() != res_id.type_id()) {
     diag->Error(DiagMessage(symbol.source)
                 << "trying to add resource '" << name << "' with ID " << res_id
                 << " but type '" << type->type << "' already has ID "
@@ -499,8 +496,7 @@
   }
 
   ResourceEntry* entry = type->FindOrCreateEntry(name.entry);
-  if (res_id.is_valid() && entry->id &&
-      entry->id.value() != res_id.entry_id()) {
+  if (res_id.is_valid_dynamic() && entry->id && entry->id.value() != res_id.entry_id()) {
     diag->Error(DiagMessage(symbol.source)
                 << "trying to add resource '" << name << "' with ID " << res_id
                 << " but resource already has ID "
@@ -509,7 +505,7 @@
     return false;
   }
 
-  if (res_id.is_valid()) {
+  if (res_id.is_valid_dynamic()) {
     package->id = res_id.package_id();
     type->id = res_id.type_id();
     entry->id = res_id.entry_id();
diff --git a/tools/aapt2/ResourceTable.h b/tools/aapt2/ResourceTable.h
index 0fe966c..6b69aaf 100644
--- a/tools/aapt2/ResourceTable.h
+++ b/tools/aapt2/ResourceTable.h
@@ -158,11 +158,8 @@
   DISALLOW_COPY_AND_ASSIGN(ResourceTableType);
 };
 
-enum class PackageType { System, Vendor, App, Dynamic };
-
 class ResourceTablePackage {
  public:
-  PackageType type = PackageType::App;
   Maybe<uint8_t> id;
   std::string name;
 
@@ -241,6 +238,19 @@
   Maybe<SearchResult> FindResource(const ResourceNameRef& name);
 
   /**
+   * Returns the package struct with the given name, or nullptr if such a
+   * package does not
+   * exist. The empty string is a valid package and typically is used to
+   * represent the
+   * 'current' package before it is known to the ResourceTable.
+   */
+  ResourceTablePackage* FindPackage(const android::StringPiece& name);
+
+  ResourceTablePackage* FindPackageById(uint8_t id);
+
+  ResourceTablePackage* CreatePackage(const android::StringPiece& name, Maybe<uint8_t> id = {});
+
+  /**
    * The string pool used by this resource table. Values that reference strings
    * must use
    * this pool to create their strings.
@@ -259,18 +269,9 @@
    */
   std::vector<std::unique_ptr<ResourceTablePackage>> packages;
 
-  /**
-   * Returns the package struct with the given name, or nullptr if such a
-   * package does not
-   * exist. The empty string is a valid package and typically is used to
-   * represent the
-   * 'current' package before it is known to the ResourceTable.
-   */
-  ResourceTablePackage* FindPackage(const android::StringPiece& name);
-
-  ResourceTablePackage* FindPackageById(uint8_t id);
-
-  ResourceTablePackage* CreatePackage(const android::StringPiece& name, Maybe<uint8_t> id = {});
+  // Set of dynamic packages that this table may reference. Their package names get encoded
+  // into the resources.arsc along with their compile-time assigned IDs.
+  std::map<size_t, std::string> included_packages_;
 
  private:
   ResourceTablePackage* FindOrCreatePackage(const android::StringPiece& name);
diff --git a/tools/aapt2/ResourceUtils.cpp b/tools/aapt2/ResourceUtils.cpp
index 150dc58..ca6738b 100644
--- a/tools/aapt2/ResourceUtils.cpp
+++ b/tools/aapt2/ResourceUtils.cpp
@@ -469,7 +469,7 @@
   if (android::ResTable::stringToInt(str16.data(), str16.size(), &value)) {
     if (value.dataType == android::Res_value::TYPE_INT_HEX) {
       ResourceId id(value.data);
-      if (id.is_valid()) {
+      if (id.is_valid_dynamic()) {
         return id;
       }
     }
@@ -533,6 +533,7 @@
     case android::Res_value::TYPE_REFERENCE:
     case android::Res_value::TYPE_ATTRIBUTE:
     case android::Res_value::TYPE_DYNAMIC_REFERENCE:
+    case android::Res_value::TYPE_DYNAMIC_ATTRIBUTE:
       return android::ResTable_map::TYPE_REFERENCE;
 
     case android::Res_value::TYPE_STRING:
diff --git a/tools/aapt2/ResourceValues.cpp b/tools/aapt2/ResourceValues.cpp
index f75ed7a..2868b2a 100644
--- a/tools/aapt2/ResourceValues.cpp
+++ b/tools/aapt2/ResourceValues.cpp
@@ -88,10 +88,24 @@
 }
 
 bool Reference::Flatten(android::Res_value* out_value) const {
-  out_value->dataType = (reference_type == Reference::Type::kResource)
-                            ? android::Res_value::TYPE_REFERENCE
-                            : android::Res_value::TYPE_ATTRIBUTE;
-  out_value->data = util::HostToDevice32(id ? id.value().id : 0);
+  const ResourceId resid = id.value_or_default(ResourceId(0));
+  const bool dynamic =
+      (resid.package_id() != kFrameworkPackageId && resid.package_id() != kAppPackageId);
+
+  if (reference_type == Reference::Type::kResource) {
+    if (dynamic) {
+      out_value->dataType = android::Res_value::TYPE_DYNAMIC_REFERENCE;
+    } else {
+      out_value->dataType = android::Res_value::TYPE_REFERENCE;
+    }
+  } else {
+    if (dynamic) {
+      out_value->dataType = android::Res_value::TYPE_DYNAMIC_ATTRIBUTE;
+    } else {
+      out_value->dataType = android::Res_value::TYPE_ATTRIBUTE;
+    }
+  }
+  out_value->data = util::HostToDevice32(resid.id);
   return true;
 }
 
diff --git a/tools/aapt2/ValueVisitor.h b/tools/aapt2/ValueVisitor.h
index 1cb6aa1..2763d49 100644
--- a/tools/aapt2/ValueVisitor.h
+++ b/tools/aapt2/ValueVisitor.h
@@ -29,7 +29,8 @@
 struct RawValueVisitor {
   virtual ~RawValueVisitor() = default;
 
-  virtual void VisitItem(Item* value) {}
+  virtual void VisitAny(Value* value) {}
+  virtual void VisitItem(Item* value) { VisitAny(value); }
   virtual void Visit(Reference* value) { VisitItem(value); }
   virtual void Visit(RawString* value) { VisitItem(value); }
   virtual void Visit(String* value) { VisitItem(value); }
@@ -38,11 +39,11 @@
   virtual void Visit(Id* value) { VisitItem(value); }
   virtual void Visit(BinaryPrimitive* value) { VisitItem(value); }
 
-  virtual void Visit(Attribute* value) {}
-  virtual void Visit(Style* value) {}
-  virtual void Visit(Array* value) {}
-  virtual void Visit(Plural* value) {}
-  virtual void Visit(Styleable* value) {}
+  virtual void Visit(Attribute* value) { VisitAny(value); }
+  virtual void Visit(Style* value) { VisitAny(value); }
+  virtual void Visit(Array* value) { VisitAny(value); }
+  virtual void Visit(Plural* value) { VisitAny(value); }
+  virtual void Visit(Styleable* value) { VisitAny(value); }
 };
 
 // NOLINT, do not add parentheses around T.
diff --git a/tools/aapt2/compile/IdAssigner.h b/tools/aapt2/compile/IdAssigner.h
index 9640eb8..3dcb1eb 100644
--- a/tools/aapt2/compile/IdAssigner.h
+++ b/tools/aapt2/compile/IdAssigner.h
@@ -26,11 +26,8 @@
 
 namespace aapt {
 
-/**
- * Assigns IDs to each resource in the table, respecting existing IDs and
- * filling in gaps
- * in between fixed ID assignments.
- */
+// Assigns IDs to each resource in the table, respecting existing IDs and
+// filling in gaps in between fixed ID assignments.
 class IdAssigner : public IResourceTableConsumer {
  public:
   IdAssigner() = default;
diff --git a/tools/aapt2/diff/Diff.cpp b/tools/aapt2/diff/Diff.cpp
index acebeda..c877468 100644
--- a/tools/aapt2/diff/Diff.cpp
+++ b/tools/aapt2/diff/Diff.cpp
@@ -28,6 +28,8 @@
 
 class DiffContext : public IAaptContext {
  public:
+  DiffContext() : name_mangler_({}), symbol_table_(&name_mangler_) {}
+
   const std::string& GetCompilationPackage() override { return empty_; }
 
   uint8_t GetPackageId() override { return 0x0; }
@@ -45,7 +47,7 @@
  private:
   std::string empty_;
   StdErrDiagnostics diagnostics_;
-  NameMangler name_mangler_ = NameMangler(NameManglerPolicy{});
+  NameMangler name_mangler_;
   SymbolTable symbol_table_;
 };
 
diff --git a/tools/aapt2/flatten/TableFlattener.cpp b/tools/aapt2/flatten/TableFlattener.cpp
index 697b07f..3098458 100644
--- a/tools/aapt2/flatten/TableFlattener.cpp
+++ b/tools/aapt2/flatten/TableFlattener.cpp
@@ -217,16 +217,17 @@
 
 class PackageFlattener {
  public:
-  PackageFlattener(IAaptContext* context, ResourceTablePackage* package, bool use_sparse_entries)
+  PackageFlattener(IAaptContext* context, ResourceTablePackage* package,
+                   const std::map<size_t, std::string>* shared_libs, bool use_sparse_entries)
       : context_(context),
         diag_(context->GetDiagnostics()),
         package_(package),
+        shared_libs_(shared_libs),
         use_sparse_entries_(use_sparse_entries) {}
 
   bool FlattenPackage(BigBuffer* buffer) {
     ChunkWriter pkg_writer(buffer);
-    ResTable_package* pkg_header =
-        pkg_writer.StartChunk<ResTable_package>(RES_TABLE_PACKAGE_TYPE);
+    ResTable_package* pkg_header = pkg_writer.StartChunk<ResTable_package>(RES_TABLE_PACKAGE_TYPE);
     pkg_header->id = util::HostToDevice32(package_->id.value());
 
     if (package_->name.size() >= arraysize(pkg_header->name)) {
@@ -253,6 +254,11 @@
     // Append the types.
     buffer->AppendBuffer(std::move(type_buffer));
 
+    // If there are libraries (or if the package ID is 0x00), encode a library chunk.
+    if (package_->id.value() == 0x00 || !shared_libs_->empty()) {
+      FlattenLibrarySpec(buffer);
+    }
+
     pkg_writer.Finish();
     return true;
   }
@@ -470,6 +476,10 @@
       type_pool_.MakeRef(ToString(type->type));
 
       std::vector<ResourceEntry*> sorted_entries = CollectAndSortEntries(type);
+      if (sorted_entries.empty()) {
+        continue;
+      }
+
       if (!FlattenTypeSpec(type, &sorted_entries, buffer)) {
         return false;
       }
@@ -504,9 +514,38 @@
     return true;
   }
 
+  void FlattenLibrarySpec(BigBuffer* buffer) {
+    ChunkWriter lib_writer(buffer);
+    ResTable_lib_header* lib_header =
+        lib_writer.StartChunk<ResTable_lib_header>(RES_TABLE_LIBRARY_TYPE);
+
+    const size_t num_entries = (package_->id.value() == 0x00 ? 1 : 0) + shared_libs_->size();
+    CHECK(num_entries > 0);
+
+    lib_header->count = util::HostToDevice32(num_entries);
+
+    ResTable_lib_entry* lib_entry = buffer->NextBlock<ResTable_lib_entry>(num_entries);
+    if (package_->id.value() == 0x00) {
+      // Add this package
+      lib_entry->packageId = util::HostToDevice32(0x00);
+      strcpy16_htod(lib_entry->packageName, arraysize(lib_entry->packageName),
+                    util::Utf8ToUtf16(package_->name));
+      ++lib_entry;
+    }
+
+    for (auto& map_entry : *shared_libs_) {
+      lib_entry->packageId = util::HostToDevice32(map_entry.first);
+      strcpy16_htod(lib_entry->packageName, arraysize(lib_entry->packageName),
+                    util::Utf8ToUtf16(map_entry.second));
+      ++lib_entry;
+    }
+    lib_writer.Finish();
+  }
+
   IAaptContext* context_;
   IDiagnostics* diag_;
   ResourceTablePackage* package_;
+  const std::map<size_t, std::string>* shared_libs_;
   bool use_sparse_entries_;
   StringPool type_pool_;
   StringPool key_pool_;
@@ -542,7 +581,8 @@
 
   // Flatten each package.
   for (auto& package : table->packages) {
-    PackageFlattener flattener(context, package.get(), options_.use_sparse_entries);
+    PackageFlattener flattener(context, package.get(), &table->included_packages_,
+                               options_.use_sparse_entries);
     if (!flattener.FlattenPackage(&package_buffer)) {
       return false;
     }
diff --git a/tools/aapt2/flatten/TableFlattener_test.cpp b/tools/aapt2/flatten/TableFlattener_test.cpp
index ff71742..4196187 100644
--- a/tools/aapt2/flatten/TableFlattener_test.cpp
+++ b/tools/aapt2/flatten/TableFlattener_test.cpp
@@ -56,13 +56,13 @@
       return result;
     }
 
-    if (out_table->add(content.data(), content.size(), -1, true) != NO_ERROR) {
+    if (out_table->add(content.data(), content.size(), 1, true) != NO_ERROR) {
       return ::testing::AssertionFailure() << "flattened ResTable is corrupt";
     }
     return ::testing::AssertionSuccess();
   }
 
-  ::testing::AssertionResult Flatten(IAaptContext* context, const TableFlattenerOptions options,
+  ::testing::AssertionResult Flatten(IAaptContext* context, const TableFlattenerOptions& options,
                                      ResourceTable* table, ResourceTable* out_table) {
     std::string content;
     auto result = Flatten(context, options, table, &content);
@@ -359,4 +359,56 @@
   EXPECT_EQ(no_sparse_contents.size(), sparse_contents.size());
 }
 
+TEST_F(TableFlattenerTest, FlattenSharedLibrary) {
+  std::unique_ptr<IAaptContext> context =
+      test::ContextBuilder().SetCompilationPackage("lib").SetPackageId(0x00).Build();
+  std::unique_ptr<ResourceTable> table =
+      test::ResourceTableBuilder()
+          .SetPackageId("lib", 0x00)
+          .AddValue("lib:id/foo", ResourceId(0x00010000), util::make_unique<Id>())
+          .Build();
+  ResourceTable result;
+  ASSERT_TRUE(Flatten(context.get(), {}, table.get(), &result));
+
+  Maybe<ResourceTable::SearchResult> search_result =
+      result.FindResource(test::ParseNameOrDie("lib:id/foo"));
+  AAPT_ASSERT_TRUE(search_result);
+  EXPECT_EQ(0x00u, search_result.value().package->id.value());
+
+  auto iter = result.included_packages_.find(0x00);
+  ASSERT_NE(result.included_packages_.end(), iter);
+  EXPECT_EQ("lib", iter->second);
+}
+
+TEST_F(TableFlattenerTest, FlattenTableReferencingSharedLibraries) {
+  std::unique_ptr<IAaptContext> context =
+      test::ContextBuilder().SetCompilationPackage("app").SetPackageId(0x7f).Build();
+  std::unique_ptr<ResourceTable> table =
+      test::ResourceTableBuilder()
+          .SetPackageId("app", 0x7f)
+          .AddValue("app:id/foo", ResourceId(0x7f010000),
+                    test::BuildReference("lib_one:id/foo", ResourceId(0x02010000)))
+          .AddValue("app:id/bar", ResourceId(0x7f010001),
+                    test::BuildReference("lib_two:id/bar", ResourceId(0x03010000)))
+          .Build();
+  table->included_packages_[0x02] = "lib_one";
+  table->included_packages_[0x03] = "lib_two";
+
+  ResTable result;
+  ASSERT_TRUE(Flatten(context.get(), {}, table.get(), &result));
+
+  const DynamicRefTable* dynamic_ref_table = result.getDynamicRefTableForCookie(1);
+  ASSERT_NE(nullptr, dynamic_ref_table);
+
+  const KeyedVector<String16, uint8_t> entries = dynamic_ref_table->entries();
+
+  ssize_t idx = entries.indexOfKey(android::String16("lib_one"));
+  ASSERT_GE(idx, 0);
+  EXPECT_EQ(0x02u, entries.valueAt(idx));
+
+  idx = entries.indexOfKey(android::String16("lib_two"));
+  ASSERT_GE(idx, 0);
+  EXPECT_EQ(0x03u, entries.valueAt(idx));
+}
+
 }  // namespace aapt
diff --git a/tools/aapt2/java/ClassDefinition.cpp b/tools/aapt2/java/ClassDefinition.cpp
index 53d6ea1..0cec9ae 100644
--- a/tools/aapt2/java/ClassDefinition.cpp
+++ b/tools/aapt2/java/ClassDefinition.cpp
@@ -22,6 +22,23 @@
 
 namespace aapt {
 
+void ClassMember::WriteToStream(const StringPiece& prefix, bool final, std::ostream* out) const {
+  processor_.WriteToStream(out, prefix);
+}
+
+void MethodDefinition::AppendStatement(const StringPiece& statement) {
+  statements_.push_back(statement.to_string());
+}
+
+void MethodDefinition::WriteToStream(const StringPiece& prefix, bool final,
+                                     std::ostream* out) const {
+  *out << prefix << signature_ << " {\n";
+  for (const auto& statement : statements_) {
+    *out << prefix << "  " << statement << "\n";
+  }
+  *out << prefix << "}";
+}
+
 bool ClassDefinition::empty() const {
   for (const std::unique_ptr<ClassMember>& member : members_) {
     if (!member->empty()) {
@@ -40,7 +57,7 @@
   ClassMember::WriteToStream(prefix, final, out);
 
   *out << prefix << "public ";
-  if (qualifier_ == ClassQualifier::Static) {
+  if (qualifier_ == ClassQualifier::kStatic) {
     *out << "static ";
   }
   *out << "final class " << name_ << " {\n";
diff --git a/tools/aapt2/java/ClassDefinition.h b/tools/aapt2/java/ClassDefinition.h
index 64e4b29..ca76421 100644
--- a/tools/aapt2/java/ClassDefinition.h
+++ b/tools/aapt2/java/ClassDefinition.h
@@ -41,10 +41,11 @@
 
   virtual bool empty() const = 0;
 
+  // Writes the class member to the out stream. Subclasses should derive this method
+  // to write their own data. Call this base method from the subclass to write out
+  // this member's comments/annotations.
   virtual void WriteToStream(const android::StringPiece& prefix, bool final,
-                             std::ostream* out) const {
-    processor_.WriteToStream(out, prefix);
-  }
+                             std::ostream* out) const;
 
  private:
   AnnotationProcessor processor_;
@@ -142,7 +143,29 @@
 
 using ResourceArrayMember = PrimitiveArrayMember<ResourceId>;
 
-enum class ClassQualifier { None, Static };
+// Represents a method in a class.
+class MethodDefinition : public ClassMember {
+ public:
+  // Expected method signature example: 'public static void onResourcesLoaded(int p)'.
+  explicit MethodDefinition(const android::StringPiece& signature)
+      : signature_(signature.to_string()) {}
+
+  // Appends a single statement to the method. It should include no newlines or else
+  // formatting may be broken.
+  void AppendStatement(const android::StringPiece& statement);
+
+  // Even if the method is empty, we always want to write the method signature.
+  bool empty() const override { return false; }
+
+  void WriteToStream(const android::StringPiece& prefix, bool final,
+                     std::ostream* out) const override;
+
+ private:
+  std::string signature_;
+  std::vector<std::string> statements_;
+};
+
+enum class ClassQualifier { kNone, kStatic };
 
 class ClassDefinition : public ClassMember {
  public:
diff --git a/tools/aapt2/java/JavaClassGenerator.cpp b/tools/aapt2/java/JavaClassGenerator.cpp
index b71dc48..68bdb95 100644
--- a/tools/aapt2/java/JavaClassGenerator.cpp
+++ b/tools/aapt2/java/JavaClassGenerator.cpp
@@ -23,6 +23,7 @@
 #include <tuple>
 
 #include "android-base/logging.h"
+#include "android-base/stringprintf.h"
 #include "androidfw/StringPiece.h"
 
 #include "NameMangler.h"
@@ -35,6 +36,7 @@
 #include "process/SymbolTable.h"
 
 using android::StringPiece;
+using android::base::StringPrintf;
 
 namespace aapt {
 
@@ -55,11 +57,9 @@
   return sJavaIdentifiers.find(symbol) == sJavaIdentifiers.end();
 }
 
-/*
- * Java symbols can not contain . or -, but those are valid in a resource name.
- * Replace those with '_'.
- */
-static std::string Transform(const StringPiece& symbol) {
+// Java symbols can not contain . or -, but those are valid in a resource name.
+// Replace those with '_'.
+static std::string TransformToFieldName(const StringPiece& symbol) {
   std::string output = symbol.to_string();
   for (char& c : output) {
     if (c == '.' || c == '-') {
@@ -69,34 +69,31 @@
   return output;
 }
 
-/**
- * Transforms an attribute in a styleable to the Java field name:
- *
- * <declare-styleable name="Foo">
- *   <attr name="android:bar" />
- *   <attr name="bar" />
- * </declare-styleable>
- *
- * Foo_android_bar
- * Foo_bar
- */
-static std::string TransformNestedAttr(
-    const ResourceNameRef& attr_name, const std::string& styleable_class_name,
-    const StringPiece& package_name_to_generate) {
+// Transforms an attribute in a styleable to the Java field name:
+//
+// <declare-styleable name="Foo">
+//   <attr name="android:bar" />
+//   <attr name="bar" />
+// </declare-styleable>
+//
+// Foo_android_bar
+// Foo_bar
+static std::string TransformNestedAttr(const ResourceNameRef& attr_name,
+                                       const std::string& styleable_class_name,
+                                       const StringPiece& package_name_to_generate) {
   std::string output = styleable_class_name;
 
   // We may reference IDs from other packages, so prefix the entry name with
   // the package.
   if (!attr_name.package.empty() &&
       package_name_to_generate != attr_name.package) {
-    output += "_" + Transform(attr_name.package);
+    output += "_" + TransformToFieldName(attr_name.package);
   }
-  output += "_" + Transform(attr_name.entry);
+  output += "_" + TransformToFieldName(attr_name.entry);
   return output;
 }
 
-static void AddAttributeFormatDoc(AnnotationProcessor* processor,
-                                  Attribute* attr) {
+static void AddAttributeFormatDoc(AnnotationProcessor* processor, Attribute* attr) {
   const uint32_t type_mask = attr->type_mask;
   if (type_mask & android::ResTable_map::TYPE_REFERENCE) {
     processor->AppendComment(
@@ -128,7 +125,7 @@
     processor->AppendComment(
         "<p>May be a color value, in the form of "
         "\"<code>#<i>rgb</i></code>\",\n"
-        "\"<code>#<i>argb</i></code>\", \"<code>#<i>rrggbb</i></code\", or \n"
+        "\"<code>#<i>argb</i></code>\", \"<code>#<i>rrggbb</i></code>\", or \n"
         "\"<code>#<i>aarrggbb</i></code>\".");
   }
 
@@ -202,18 +199,21 @@
   return true;
 }
 
+// Whether or not to skip writing this symbol.
+bool JavaClassGenerator::SkipSymbol(const Maybe<SymbolTable::Symbol>& symbol) {
+  return !symbol || (options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic &&
+                     !symbol.value().is_public);
+}
+
 struct StyleableAttr {
-  const Reference* attr_ref;
+  const Reference* attr_ref = nullptr;
   std::string field_name;
-  std::unique_ptr<SymbolTable::Symbol> symbol;
+  Maybe<SymbolTable::Symbol> symbol;
 };
 
-static bool less_styleable_attr(const StyleableAttr& lhs,
-                                const StyleableAttr& rhs) {
-  const ResourceId lhs_id =
-      lhs.attr_ref->id ? lhs.attr_ref->id.value() : ResourceId(0);
-  const ResourceId rhs_id =
-      rhs.attr_ref->id ? rhs.attr_ref->id.value() : ResourceId(0);
+static bool operator<(const StyleableAttr& lhs, const StyleableAttr& rhs) {
+  const ResourceId lhs_id = lhs.attr_ref->id.value_or_default(ResourceId(0));
+  const ResourceId rhs_id = rhs.attr_ref->id.value_or_default(ResourceId(0));
   if (lhs_id < rhs_id) {
     return true;
   } else if (lhs_id > rhs_id) {
@@ -223,72 +223,57 @@
   }
 }
 
-void JavaClassGenerator::AddMembersToStyleableClass(
-    const StringPiece& package_name_to_generate, const std::string& entry_name,
-    const Styleable* styleable, ClassDefinition* out_styleable_class_def) {
-  const std::string class_name = Transform(entry_name);
+void JavaClassGenerator::ProcessStyleable(const ResourceNameRef& name, const ResourceId& id,
+                                          const Styleable& styleable,
+                                          const StringPiece& package_name_to_generate,
+                                          ClassDefinition* out_class_def,
+                                          MethodDefinition* out_rewrite_method) {
+  const std::string array_field_name = TransformToFieldName(name.entry);
+  std::unique_ptr<ResourceArrayMember> array_def =
+      util::make_unique<ResourceArrayMember>(array_field_name);
 
-  std::unique_ptr<ResourceArrayMember> styleable_array_def =
-      util::make_unique<ResourceArrayMember>(class_name);
-
-  // This must be sorted by resource ID.
+  // The array must be sorted by resource ID.
   std::vector<StyleableAttr> sorted_attributes;
-  sorted_attributes.reserve(styleable->entries.size());
-  for (const auto& attr : styleable->entries) {
+  sorted_attributes.reserve(styleable.entries.size());
+  for (const auto& attr : styleable.entries) {
     // If we are not encoding final attributes, the styleable entry may have no
     // ID if we are building a static library.
     CHECK(!options_.use_final || attr.id) << "no ID set for Styleable entry";
     CHECK(bool(attr.name)) << "no name set for Styleable entry";
 
-    // We will need the unmangled, transformed name in the comments and the
-    // field,
+    // We will need the unmangled, transformed name in the comments and the field,
     // so create it once and cache it in this StyleableAttr data structure.
-    StyleableAttr styleable_attr = {};
+    StyleableAttr styleable_attr;
     styleable_attr.attr_ref = &attr;
-    styleable_attr.field_name = TransformNestedAttr(
-        attr.name.value(), class_name, package_name_to_generate);
 
-    Reference mangled_reference;
-    mangled_reference.id = attr.id;
-    mangled_reference.name = attr.name;
-    if (mangled_reference.name.value().package.empty()) {
-      mangled_reference.name.value().package =
-          context_->GetCompilationPackage();
-    }
+    // The field name for this attribute is prefixed by the name of this styleable and
+    // the package it comes from.
+    styleable_attr.field_name =
+        TransformNestedAttr(attr.name.value(), array_field_name, package_name_to_generate);
 
-    if (Maybe<ResourceName> mangled_name =
-            context_->GetNameMangler()->MangleName(
-                mangled_reference.name.value())) {
-      mangled_reference.name = mangled_name;
-    }
-
-    // Look up the symbol so that we can write out in the comments what are
-    // possible
-    // legal values for this attribute.
-    const SymbolTable::Symbol* symbol =
-        context_->GetExternalSymbols()->FindByReference(mangled_reference);
+    // Look up the symbol so that we can write out in the comments what are possible legal values
+    // for this attribute.
+    const SymbolTable::Symbol* symbol = context_->GetExternalSymbols()->FindByReference(attr);
     if (symbol && symbol->attribute) {
-      // Copy the symbol data structure because the returned instance can be
-      // destroyed.
-      styleable_attr.symbol = util::make_unique<SymbolTable::Symbol>(*symbol);
+      // Copy the symbol data structure because the returned instance can be destroyed.
+      styleable_attr.symbol = *symbol;
     }
     sorted_attributes.push_back(std::move(styleable_attr));
   }
 
   // Sort the attributes by ID.
-  std::sort(sorted_attributes.begin(), sorted_attributes.end(),
-            less_styleable_attr);
+  std::sort(sorted_attributes.begin(), sorted_attributes.end());
 
+  // Build the JavaDoc comment for the Styleable array. This has references to child attributes
+  // and what possible values can be used for them.
   const size_t attr_count = sorted_attributes.size();
   if (attr_count > 0) {
-    // Build the comment string for the Styleable. It includes details about the
-    // child attributes.
     std::stringstream styleable_comment;
-    if (!styleable->GetComment().empty()) {
-      styleable_comment << styleable->GetComment() << "\n";
+    if (!styleable.GetComment().empty()) {
+      styleable_comment << styleable.GetComment() << "\n";
     } else {
-      styleable_comment << "Attributes that can be used with a " << class_name
-                        << ".\n";
+      // Apply a default intro comment if the styleable has no comments of its own.
+      styleable_comment << "Attributes that can be used with a " << array_field_name << ".\n";
     }
 
     styleable_comment << "<p>Includes the following attributes:</p>\n"
@@ -297,22 +282,16 @@
                          "<colgroup align=\"left\" />\n"
                          "<tr><th>Attribute</th><th>Description</th></tr>\n";
 
+    // Build the table of attributes with their links and names.
     for (const StyleableAttr& entry : sorted_attributes) {
-      if (!entry.symbol) {
+      if (SkipSymbol(entry.symbol)) {
         continue;
       }
 
-      if (options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic &&
-          !entry.symbol->is_public) {
-        // Don't write entries for non-public attributes.
-        continue;
-      }
-
-      StringPiece attr_comment_line = entry.symbol->attribute->GetComment();
+      StringPiece attr_comment_line = entry.symbol.value().attribute->GetComment();
       if (attr_comment_line.contains("@removed")) {
         // Removed attributes are public but hidden from the documentation, so
-        // don't emit
-        // them as part of the class documentation.
+        // don't emit them as part of the class documentation.
         continue;
       }
 
@@ -327,71 +306,52 @@
 
       styleable_comment << "<td>";
 
-      // Only use the comment up until the first '.'. This is to stay compatible
-      // with
-      // the way old AAPT did it (presumably to keep it short and to avoid
-      // including
+      // Only use the comment up until the first '.'. This is to stay compatible with
+      // the way old AAPT did it (presumably to keep it short and to avoid including
       // annotations like @hide which would affect this Styleable).
-      auto iter =
-          std::find(attr_comment_line.begin(), attr_comment_line.end(), u'.');
+      auto iter = std::find(attr_comment_line.begin(), attr_comment_line.end(), '.');
       if (iter != attr_comment_line.end()) {
-        attr_comment_line =
-            attr_comment_line.substr(0, (iter - attr_comment_line.begin()) + 1);
+        attr_comment_line = attr_comment_line.substr(0, (iter - attr_comment_line.begin()) + 1);
       }
       styleable_comment << attr_comment_line << "</td></tr>\n";
     }
     styleable_comment << "</table>\n";
 
+    // Generate the @see lines for each attribute.
     for (const StyleableAttr& entry : sorted_attributes) {
-      if (!entry.symbol) {
-        continue;
-      }
-
-      if (options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic &&
-          !entry.symbol->is_public) {
-        // Don't write entries for non-public attributes.
+      if (SkipSymbol(entry.symbol)) {
         continue;
       }
       styleable_comment << "@see #" << entry.field_name << "\n";
     }
 
-    styleable_array_def->GetCommentBuilder()->AppendComment(
-        styleable_comment.str());
+    array_def->GetCommentBuilder()->AppendComment(styleable_comment.str());
   }
 
   // Add the ResourceIds to the array member.
   for (const StyleableAttr& styleable_attr : sorted_attributes) {
-    styleable_array_def->AddElement(styleable_attr.attr_ref->id
-                                        ? styleable_attr.attr_ref->id.value()
-                                        : ResourceId(0));
+    const ResourceId id = styleable_attr.attr_ref->id.value_or_default(ResourceId(0));
+    array_def->AddElement(id);
   }
 
   // Add the Styleable array to the Styleable class.
-  out_styleable_class_def->AddMember(std::move(styleable_array_def));
+  out_class_def->AddMember(std::move(array_def));
 
   // Now we emit the indices into the array.
   for (size_t i = 0; i < attr_count; i++) {
     const StyleableAttr& styleable_attr = sorted_attributes[i];
-
-    if (!styleable_attr.symbol) {
-      continue;
-    }
-
-    if (options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic &&
-        !styleable_attr.symbol->is_public) {
-      // Don't write entries for non-public attributes.
+    if (SkipSymbol(styleable_attr.symbol)) {
       continue;
     }
 
     StringPiece comment = styleable_attr.attr_ref->GetComment();
-    if (styleable_attr.symbol->attribute && comment.empty()) {
-      comment = styleable_attr.symbol->attribute->GetComment();
+    if (styleable_attr.symbol.value().attribute && comment.empty()) {
+      comment = styleable_attr.symbol.value().attribute->GetComment();
     }
 
     if (comment.contains("@removed")) {
       // Removed attributes are public but hidden from the documentation, so
-      // don't emit them
-      // as part of the class documentation.
+      // don't emit them as part of the class documentation.
       continue;
     }
 
@@ -414,114 +374,151 @@
       std::stringstream default_comment;
       default_comment << "<p>This symbol is the offset where the "
                       << "{@link " << package_name << ".R.attr#"
-                      << Transform(attr_name.entry) << "}\n"
+                      << TransformToFieldName(attr_name.entry) << "}\n"
                       << "attribute's value can be found in the "
-                      << "{@link #" << class_name << "} array.";
+                      << "{@link #" << array_field_name << "} array.";
       attr_processor->AppendComment(default_comment.str());
     }
 
     attr_processor->AppendNewLine();
-
-    AddAttributeFormatDoc(attr_processor,
-                          styleable_attr.symbol->attribute.get());
+    AddAttributeFormatDoc(attr_processor, styleable_attr.symbol.value().attribute.get());
     attr_processor->AppendNewLine();
+    attr_processor->AppendComment(
+        StringPrintf("@attr name %s:%s", package_name.data(), attr_name.entry.data()));
 
-    std::stringstream doclava_name;
-    doclava_name << "@attr name " << package_name << ":" << attr_name.entry;
+    out_class_def->AddMember(std::move(index_member));
+  }
 
-    attr_processor->AppendComment(doclava_name.str());
-
-    out_styleable_class_def->AddMember(std::move(index_member));
+  // If there is a rewrite method to generate, add the statements that rewrite package IDs
+  // for this styleable.
+  if (out_rewrite_method != nullptr) {
+    out_rewrite_method->AppendStatement(
+        StringPrintf("for (int i = 0; i < styleable.%s.length; i++) {", array_field_name.data()));
+    out_rewrite_method->AppendStatement(
+        StringPrintf("  if ((styleable.%s[i] & 0xff000000) == 0) {", array_field_name.data()));
+    out_rewrite_method->AppendStatement(
+        StringPrintf("    styleable.%s[i] = (styleable.%s[i] & 0x00ffffff) | (p << 24);",
+                     array_field_name.data(), array_field_name.data()));
+    out_rewrite_method->AppendStatement("  }");
+    out_rewrite_method->AppendStatement("}");
   }
 }
 
-bool JavaClassGenerator::AddMembersToTypeClass(
-    const StringPiece& package_name_to_generate,
-    const ResourceTablePackage* package, const ResourceTableType* type,
-    ClassDefinition* out_type_class_def) {
-  for (const auto& entry : type->entries) {
-    if (SkipSymbol(entry->symbol_status.state)) {
+void JavaClassGenerator::ProcessResource(const ResourceNameRef& name, const ResourceId& id,
+                                         const ResourceEntry& entry, ClassDefinition* out_class_def,
+                                         MethodDefinition* out_rewrite_method) {
+  const std::string field_name = TransformToFieldName(name.entry);
+  std::unique_ptr<ResourceMember> resource_member =
+      util::make_unique<ResourceMember>(field_name, id);
+
+  // Build the comments and annotations for this entry.
+  AnnotationProcessor* processor = resource_member->GetCommentBuilder();
+
+  // Add the comments from any <public> tags.
+  if (entry.symbol_status.state != SymbolState::kUndefined) {
+    processor->AppendComment(entry.symbol_status.comment);
+  }
+
+  // Add the comments from all configurations of this entry.
+  for (const auto& config_value : entry.values) {
+    processor->AppendComment(config_value->value->GetComment());
+  }
+
+  // If this is an Attribute, append the format Javadoc.
+  if (!entry.values.empty()) {
+    if (Attribute* attr = ValueCast<Attribute>(entry.values.front()->value.get())) {
+      // We list out the available values for the given attribute.
+      AddAttributeFormatDoc(processor, attr);
+    }
+  }
+
+  out_class_def->AddMember(std::move(resource_member));
+
+  if (out_rewrite_method != nullptr) {
+    const StringPiece& type_str = ToString(name.type);
+    out_rewrite_method->AppendStatement(StringPrintf("%s.%s = (%s.%s & 0x00ffffff) | (p << 24);",
+                                                     type_str.data(), field_name.data(),
+                                                     type_str.data(), field_name.data()));
+  }
+}
+
+Maybe<std::string> JavaClassGenerator::UnmangleResource(const StringPiece& package_name,
+                                                        const StringPiece& package_name_to_generate,
+                                                        const ResourceEntry& entry) {
+  if (SkipSymbol(entry.symbol_status.state)) {
+    return {};
+  }
+
+  std::string unmangled_package;
+  std::string unmangled_name = entry.name;
+  if (NameMangler::Unmangle(&unmangled_name, &unmangled_package)) {
+    // The entry name was mangled, and we successfully unmangled it.
+    // Check that we want to emit this symbol.
+    if (package_name != unmangled_package) {
+      // Skip the entry if it doesn't belong to the package we're writing.
+      return {};
+    }
+  } else if (package_name_to_generate != package_name) {
+    // We are processing a mangled package name,
+    // but this is a non-mangled resource.
+    return {};
+  }
+  return {std::move(unmangled_name)};
+}
+
+bool JavaClassGenerator::ProcessType(const StringPiece& package_name_to_generate,
+                                     const ResourceTablePackage& package,
+                                     const ResourceTableType& type,
+                                     ClassDefinition* out_type_class_def,
+                                     MethodDefinition* out_rewrite_method_def) {
+  for (const auto& entry : type.entries) {
+    const Maybe<std::string> unmangled_name =
+        UnmangleResource(package.name, package_name_to_generate, *entry);
+    if (!unmangled_name) {
       continue;
     }
 
+    // Create an ID if there is one (static libraries don't need one).
     ResourceId id;
-    if (package->id && type->id && entry->id) {
-      id = ResourceId(package->id.value(), type->id.value(), entry->id.value());
+    if (package.id && type.id && entry->id) {
+      id = ResourceId(package.id.value(), type.id.value(), entry->id.value());
     }
 
-    std::string unmangled_package;
-    std::string unmangled_name = entry->name;
-    if (NameMangler::Unmangle(&unmangled_name, &unmangled_package)) {
-      // The entry name was mangled, and we successfully unmangled it.
-      // Check that we want to emit this symbol.
-      if (package->name != unmangled_package) {
-        // Skip the entry if it doesn't belong to the package we're writing.
-        continue;
-      }
-    } else if (package_name_to_generate != package->name) {
-      // We are processing a mangled package name,
-      // but this is a non-mangled resource.
-      continue;
-    }
+    // We need to make sure we hide the fact that we are generating kAttrPrivate attributes.
+    const ResourceNameRef resource_name(
+        package_name_to_generate,
+        type.type == ResourceType::kAttrPrivate ? ResourceType::kAttr : type.type,
+        unmangled_name.value());
 
-    if (!IsValidSymbol(unmangled_name)) {
-      ResourceNameRef resource_name(package_name_to_generate, type->type,
-                                    unmangled_name);
+    // Check to see if the unmangled name is a valid Java name (not a keyword).
+    if (!IsValidSymbol(unmangled_name.value())) {
       std::stringstream err;
       err << "invalid symbol name '" << resource_name << "'";
       error_ = err.str();
       return false;
     }
 
-    if (type->type == ResourceType::kStyleable) {
+    if (resource_name.type == ResourceType::kStyleable) {
       CHECK(!entry->values.empty());
 
       const Styleable* styleable =
           static_cast<const Styleable*>(entry->values.front()->value.get());
 
-      // Comments are handled within this method.
-      AddMembersToStyleableClass(package_name_to_generate, unmangled_name,
-                                 styleable, out_type_class_def);
+      ProcessStyleable(resource_name, id, *styleable, package_name_to_generate, out_type_class_def,
+                       out_rewrite_method_def);
     } else {
-      std::unique_ptr<ResourceMember> resource_member =
-          util::make_unique<ResourceMember>(Transform(unmangled_name), id);
-
-      // Build the comments and annotations for this entry.
-      AnnotationProcessor* processor = resource_member->GetCommentBuilder();
-
-      // Add the comments from any <public> tags.
-      if (entry->symbol_status.state != SymbolState::kUndefined) {
-        processor->AppendComment(entry->symbol_status.comment);
-      }
-
-      // Add the comments from all configurations of this entry.
-      for (const auto& config_value : entry->values) {
-        processor->AppendComment(config_value->value->GetComment());
-      }
-
-      // If this is an Attribute, append the format Javadoc.
-      if (!entry->values.empty()) {
-        if (Attribute* attr =
-                ValueCast<Attribute>(entry->values.front()->value.get())) {
-          // We list out the available values for the given attribute.
-          AddAttributeFormatDoc(processor, attr);
-        }
-      }
-
-      out_type_class_def->AddMember(std::move(resource_member));
+      ProcessResource(resource_name, id, *entry, out_type_class_def, out_rewrite_method_def);
     }
   }
   return true;
 }
 
-bool JavaClassGenerator::Generate(const StringPiece& package_name_to_generate,
-                                  std::ostream* out) {
+bool JavaClassGenerator::Generate(const StringPiece& package_name_to_generate, std::ostream* out) {
   return Generate(package_name_to_generate, package_name_to_generate, out);
 }
 
-static void AppendJavaDocAnnotations(
-    const std::vector<std::string>& annotations,
-    AnnotationProcessor* processor) {
+static void AppendJavaDocAnnotations(const std::vector<std::string>& annotations,
+                                     AnnotationProcessor* processor) {
   for (const std::string& annotation : annotations) {
     std::string proper_annotation = "@";
     proper_annotation += annotation;
@@ -532,37 +529,45 @@
 bool JavaClassGenerator::Generate(const StringPiece& package_name_to_generate,
                                   const StringPiece& out_package_name,
                                   std::ostream* out) {
-  ClassDefinition r_class("R", ClassQualifier::None, true);
+  ClassDefinition r_class("R", ClassQualifier::kNone, true);
+  std::unique_ptr<MethodDefinition> rewrite_method;
+
+  // Generate an onResourcesLoaded() callback if requested.
+  if (options_.rewrite_callback_options) {
+    rewrite_method =
+        util::make_unique<MethodDefinition>("public static void onResourcesLoaded(int p)");
+    for (const std::string& package_to_callback :
+         options_.rewrite_callback_options.value().packages_to_callback) {
+      rewrite_method->AppendStatement(
+          StringPrintf("%s.R.onResourcesLoaded(p);", package_to_callback.data()));
+    }
+  }
 
   for (const auto& package : table_->packages) {
     for (const auto& type : package->types) {
       if (type->type == ResourceType::kAttrPrivate) {
+        // We generate these as part of the kAttr type, so skip them here.
         continue;
       }
 
+      // Stay consistent with AAPT and generate an empty type class if the R class
+      // is public.
       const bool force_creation_if_empty =
           (options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic);
 
-      std::unique_ptr<ClassDefinition> class_def =
-          util::make_unique<ClassDefinition>(ToString(type->type),
-                                             ClassQualifier::Static,
-                                             force_creation_if_empty);
-
-      bool result = AddMembersToTypeClass(
-          package_name_to_generate, package.get(), type.get(), class_def.get());
-      if (!result) {
+      std::unique_ptr<ClassDefinition> class_def = util::make_unique<ClassDefinition>(
+          ToString(type->type), ClassQualifier::kStatic, force_creation_if_empty);
+      if (!ProcessType(package_name_to_generate, *package, *type, class_def.get(),
+                       rewrite_method.get())) {
         return false;
       }
 
       if (type->type == ResourceType::kAttr) {
         // Also include private attributes in this same class.
-        ResourceTableType* priv_type =
-            package->FindType(ResourceType::kAttrPrivate);
+        const ResourceTableType* priv_type = package->FindType(ResourceType::kAttrPrivate);
         if (priv_type) {
-          result =
-              AddMembersToTypeClass(package_name_to_generate, package.get(),
-                                    priv_type, class_def.get());
-          if (!result) {
+          if (!ProcessType(package_name_to_generate, *package, *priv_type, class_def.get(),
+                           rewrite_method.get())) {
             return false;
           }
         }
@@ -571,23 +576,23 @@
       if (type->type == ResourceType::kStyleable &&
           options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic) {
         // When generating a public R class, we don't want Styleable to be part
-        // of the API.
-        // It is only emitted for documentation purposes.
+        // of the API. It is only emitted for documentation purposes.
         class_def->GetCommentBuilder()->AppendComment("@doconly");
       }
 
-      AppendJavaDocAnnotations(options_.javadoc_annotations,
-                               class_def->GetCommentBuilder());
+      AppendJavaDocAnnotations(options_.javadoc_annotations, class_def->GetCommentBuilder());
 
       r_class.AddMember(std::move(class_def));
     }
   }
 
-  AppendJavaDocAnnotations(options_.javadoc_annotations,
-                           r_class.GetCommentBuilder());
+  if (rewrite_method != nullptr) {
+    r_class.AddMember(std::move(rewrite_method));
+  }
 
-  if (!ClassDefinition::WriteJavaFile(&r_class, out_package_name,
-                                      options_.use_final, out)) {
+  AppendJavaDocAnnotations(options_.javadoc_annotations, r_class.GetCommentBuilder());
+
+  if (!ClassDefinition::WriteJavaFile(&r_class, out_package_name, options_.use_final, out)) {
     return false;
   }
 
diff --git a/tools/aapt2/java/JavaClassGenerator.h b/tools/aapt2/java/JavaClassGenerator.h
index 5cf556e..4510430 100644
--- a/tools/aapt2/java/JavaClassGenerator.h
+++ b/tools/aapt2/java/JavaClassGenerator.h
@@ -25,19 +25,28 @@
 #include "ResourceTable.h"
 #include "ResourceValues.h"
 #include "process/IResourceTableConsumer.h"
+#include "process/SymbolTable.h"
 
 namespace aapt {
 
 class AnnotationProcessor;
 class ClassDefinition;
+class MethodDefinition;
+
+// Options for generating onResourcesLoaded callback in R.java.
+struct OnResourcesLoadedCallbackOptions {
+  // Other R classes to delegate the same callback to (with the same package ID).
+  std::vector<std::string> packages_to_callback;
+};
 
 struct JavaClassGeneratorOptions {
-  /*
-   * Specifies whether to use the 'final' modifier
-   * on resource entries. Default is true.
-   */
+  // Specifies whether to use the 'final' modifier on resource entries. Default is true.
   bool use_final = true;
 
+  // If set, generates code to rewrite the package ID of resources.
+  // Implies use_final == true. Default is unset.
+  Maybe<OnResourcesLoadedCallbackOptions> rewrite_callback_options;
+
   enum class SymbolTypes {
     kAll,
     kPublicPrivate,
@@ -46,47 +55,54 @@
 
   SymbolTypes types = SymbolTypes::kAll;
 
-  /**
-   * A list of JavaDoc annotations to add to the comments of all generated
-   * classes.
-   */
+  // A list of JavaDoc annotations to add to the comments of all generated classes.
   std::vector<std::string> javadoc_annotations;
 };
 
-/*
- * Generates the R.java file for a resource table.
- */
+// Generates the R.java file for a resource table.
 class JavaClassGenerator {
  public:
   JavaClassGenerator(IAaptContext* context, ResourceTable* table,
                      const JavaClassGeneratorOptions& options);
 
-  /*
-   * Writes the R.java file to `out`. Only symbols belonging to `package` are
-   * written.
-   * All symbols technically belong to a single package, but linked libraries
-   * will
-   * have their names mangled, denoting that they came from a different package.
-   * We need to generate these symbols in a separate file.
-   * Returns true on success.
-   */
-  bool Generate(const android::StringPiece& packageNameToGenerate, std::ostream* out);
+  // Writes the R.java file to `out`. Only symbols belonging to `package` are written.
+  // All symbols technically belong to a single package, but linked libraries will
+  // have their names mangled, denoting that they came from a different package.
+  // We need to generate these symbols in a separate file. Returns true on success.
+  bool Generate(const android::StringPiece& package_name_to_generate, std::ostream* out);
 
-  bool Generate(const android::StringPiece& packageNameToGenerate,
-                const android::StringPiece& outputPackageName, std::ostream* out);
+  bool Generate(const android::StringPiece& package_name_to_generate,
+                const android::StringPiece& output_package_name, std::ostream* out);
 
   const std::string& getError() const;
 
  private:
-  bool AddMembersToTypeClass(const android::StringPiece& packageNameToGenerate,
-                             const ResourceTablePackage* package, const ResourceTableType* type,
-                             ClassDefinition* outTypeClassDef);
-
-  void AddMembersToStyleableClass(const android::StringPiece& packageNameToGenerate,
-                                  const std::string& entryName, const Styleable* styleable,
-                                  ClassDefinition* outStyleableClassDef);
-
   bool SkipSymbol(SymbolState state);
+  bool SkipSymbol(const Maybe<SymbolTable::Symbol>& symbol);
+
+  // Returns the unmangled resource entry name if the unmangled package is the same as
+  // package_name_to_generate. Returns nothing if the resource should be skipped.
+  Maybe<std::string> UnmangleResource(const android::StringPiece& package_name,
+                                      const android::StringPiece& package_name_to_generate,
+                                      const ResourceEntry& entry);
+
+  bool ProcessType(const android::StringPiece& package_name_to_generate,
+                   const ResourceTablePackage& package, const ResourceTableType& type,
+                   ClassDefinition* out_type_class_def, MethodDefinition* out_rewrite_method_def);
+
+  // Writes a resource to the R.java file, optionally writing out a rewrite rule for its package
+  // ID if `out_rewrite_method` is not nullptr.
+  void ProcessResource(const ResourceNameRef& name, const ResourceId& id,
+                       const ResourceEntry& entry, ClassDefinition* out_class_def,
+                       MethodDefinition* out_rewrite_method);
+
+  // Writes a styleable resource to the R.java file, optionally writing out a rewrite rule for
+  // its package ID if `out_rewrite_method` is not nullptr.
+  // `package_name_to_generate` is the package
+  void ProcessStyleable(const ResourceNameRef& name, const ResourceId& id,
+                        const Styleable& styleable,
+                        const android::StringPiece& package_name_to_generate,
+                        ClassDefinition* out_class_def, MethodDefinition* out_rewrite_method);
 
   IAaptContext* context_;
   ResourceTable* table_;
diff --git a/tools/aapt2/java/JavaClassGenerator_test.cpp b/tools/aapt2/java/JavaClassGenerator_test.cpp
index 55c5cb2..271279f 100644
--- a/tools/aapt2/java/JavaClassGenerator_test.cpp
+++ b/tools/aapt2/java/JavaClassGenerator_test.cpp
@@ -293,8 +293,7 @@
 
 TEST(JavaClassGeneratorTest, CommentsForEnumAndFlagAttributesArePresent) {}
 
-TEST(JavaClassGeneratorTest,
-     CommentsForStyleablesAndNestedAttributesArePresent) {
+TEST(JavaClassGeneratorTest, CommentsForStyleablesAndNestedAttributesArePresent) {
   Attribute attr(false);
   attr.SetComment(StringPiece("This is an attribute"));
 
@@ -364,4 +363,37 @@
   EXPECT_EQ(std::string::npos, actual.find("removed", pos + 1));
 }
 
+TEST(JavaClassGeneratorTest, GenerateOnResourcesLoadedCallbackForSharedLibrary) {
+  std::unique_ptr<ResourceTable> table =
+      test::ResourceTableBuilder()
+          .SetPackageId("android", 0x00)
+          .AddValue("android:attr/foo", ResourceId(0x00010000), util::make_unique<Attribute>(false))
+          .AddValue("android:id/foo", ResourceId(0x00020000), util::make_unique<Id>())
+          .AddValue(
+              "android:style/foo", ResourceId(0x00030000),
+              test::StyleBuilder()
+                  .AddItem("android:attr/foo", ResourceId(0x00010000), util::make_unique<Id>())
+                  .Build())
+          .Build();
+
+  std::unique_ptr<IAaptContext> context =
+      test::ContextBuilder().SetPackageId(0x00).SetCompilationPackage("android").Build();
+
+  JavaClassGeneratorOptions options;
+  options.use_final = false;
+  options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{
+      {"com.foo", "com.boo"},
+  };
+  JavaClassGenerator generator(context.get(), table.get(), options);
+
+  std::stringstream out;
+  ASSERT_TRUE(generator.Generate("android", &out));
+
+  std::string actual = out.str();
+
+  EXPECT_NE(std::string::npos, actual.find("void onResourcesLoaded"));
+  EXPECT_NE(std::string::npos, actual.find("com.foo.R.onResourcesLoaded"));
+  EXPECT_NE(std::string::npos, actual.find("com.boo.R.onResourcesLoaded"));
+}
+
 }  // namespace aapt
diff --git a/tools/aapt2/java/ManifestClassGenerator.cpp b/tools/aapt2/java/ManifestClassGenerator.cpp
index de8e59a..f49e498 100644
--- a/tools/aapt2/java/ManifestClassGenerator.cpp
+++ b/tools/aapt2/java/ManifestClassGenerator.cpp
@@ -100,11 +100,9 @@
   }
 
   std::unique_ptr<ClassDefinition> permission_class =
-      util::make_unique<ClassDefinition>("permission", ClassQualifier::Static,
-                                         false);
+      util::make_unique<ClassDefinition>("permission", ClassQualifier::kStatic, false);
   std::unique_ptr<ClassDefinition> permission_group_class =
-      util::make_unique<ClassDefinition>("permission_group",
-                                         ClassQualifier::Static, false);
+      util::make_unique<ClassDefinition>("permission_group", ClassQualifier::kStatic, false);
 
   bool error = false;
   std::vector<xml::Element*> children = el->GetChildElements();
@@ -125,8 +123,7 @@
   }
 
   std::unique_ptr<ClassDefinition> manifest_class =
-      util::make_unique<ClassDefinition>("Manifest", ClassQualifier::None,
-                                         false);
+      util::make_unique<ClassDefinition>("Manifest", ClassQualifier::kNone, false);
   manifest_class->AddMember(std::move(permission_class));
   manifest_class->AddMember(std::move(permission_group_class));
   return manifest_class;
diff --git a/tools/aapt2/link/Link.cpp b/tools/aapt2/link/Link.cpp
index f07e20b..dd8e14b 100644
--- a/tools/aapt2/link/Link.cpp
+++ b/tools/aapt2/link/Link.cpp
@@ -46,6 +46,8 @@
 #include "link/ManifestFixer.h"
 #include "link/ReferenceLinker.h"
 #include "link/TableMerger.h"
+#include "optimize/ResourceDeduper.h"
+#include "optimize/VersionCollapser.h"
 #include "process/IResourceTableConsumer.h"
 #include "process/SymbolTable.h"
 #include "proto/ProtoSerialize.h"
@@ -59,7 +61,16 @@
 
 namespace aapt {
 
+// The type of package to build.
+enum class PackageType {
+  kApp,
+  kSharedLib,
+  kStaticLib,
+};
+
 struct LinkOptions {
+  PackageType package_type = PackageType::kApp;
+
   std::string output_path;
   std::string manifest_path;
   std::vector<std::string> include_paths;
@@ -87,7 +98,6 @@
   std::unordered_set<std::string> extensions_to_not_compress;
 
   // Static lib options.
-  bool static_lib = false;
   bool no_static_lib_packages = false;
 
   // AndroidManifest.xml massaging options.
@@ -111,7 +121,7 @@
 
 class LinkContext : public IAaptContext {
  public:
-  LinkContext() : name_mangler_({}) {}
+  LinkContext() : name_mangler_({}), symbols_(&name_mangler_) {}
 
   IDiagnostics* GetDiagnostics() override { return &diagnostics_; }
 
@@ -684,14 +694,13 @@
 
       // First try to load the file as a static lib.
       std::string error_str;
-      std::unique_ptr<ResourceTable> static_include =
-          LoadStaticLibrary(path, &error_str);
-      if (static_include) {
-        if (!options_.static_lib) {
-          // Can't include static libraries when not building a static library.
+      std::unique_ptr<ResourceTable> include_static = LoadStaticLibrary(path, &error_str);
+      if (include_static) {
+        if (options_.package_type != PackageType::kStaticLib) {
+          // Can't include static libraries when not building a static library (they have no IDs
+          // assigned).
           context_->GetDiagnostics()->Error(
-              DiagMessage(path)
-              << "can't include static library when building app");
+              DiagMessage(path) << "can't include static library when not building a static lib");
           return false;
         }
 
@@ -699,16 +708,15 @@
         // package of this
         // table to our compilation package.
         if (options_.no_static_lib_packages) {
-          if (ResourceTablePackage* pkg =
-                  static_include->FindPackageById(0x7f)) {
+          if (ResourceTablePackage* pkg = include_static->FindPackageById(0x7f)) {
             pkg->name = context_->GetCompilationPackage();
           }
         }
 
         context_->GetExternalSymbols()->AppendSource(
-            util::make_unique<ResourceTableSymbolSource>(static_include.get()));
+            util::make_unique<ResourceTableSymbolSource>(include_static.get()));
 
-        static_table_includes_.push_back(std::move(static_include));
+        static_table_includes_.push_back(std::move(include_static));
 
       } else if (!error_str.empty()) {
         // We had an error with reading, so fail.
@@ -717,12 +725,19 @@
       }
 
       if (!asset_source->AddAssetPath(path)) {
-        context_->GetDiagnostics()->Error(DiagMessage(path)
-                                          << "failed to load include path");
+        context_->GetDiagnostics()->Error(DiagMessage(path) << "failed to load include path");
         return false;
       }
     }
 
+    // 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) {
+        final_table_.included_packages_[entry.first] = entry.second;
+      }
+    }
+
     context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
     return true;
   }
@@ -1082,18 +1097,15 @@
       return false;
     }
 
-    std::unique_ptr<ResourceTable> table =
-        LoadTablePbFromCollection(collection.get());
+    std::unique_ptr<ResourceTable> table = LoadTablePbFromCollection(collection.get());
     if (!table) {
-      context_->GetDiagnostics()->Error(DiagMessage(input)
-                                        << "invalid static library");
+      context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
       return false;
     }
 
     ResourceTablePackage* pkg = table->FindPackageById(0x7f);
     if (!pkg) {
-      context_->GetDiagnostics()->Error(DiagMessage(input)
-                                        << "static library has no package");
+      context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
       return false;
     }
 
@@ -1110,11 +1122,9 @@
 
       pkg->name = "";
       if (override) {
-        result = table_merger_->MergeOverlay(Source(input), table.get(),
-                                             collection.get());
+        result = table_merger_->MergeOverlay(Source(input), table.get(), collection.get());
       } else {
-        result =
-            table_merger_->Merge(Source(input), table.get(), collection.get());
+        result = table_merger_->Merge(Source(input), table.get(), collection.get());
       }
 
     } else {
@@ -1402,7 +1412,7 @@
    */
   bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set,
                 xml::XmlResource* manifest, ResourceTable* table) {
-    const bool keep_raw_values = options_.static_lib;
+    const bool keep_raw_values = options_.package_type == PackageType::kStaticLib;
     bool result = FlattenXml(manifest, "AndroidManifest.xml", {},
                              keep_raw_values, writer, context_);
     if (!result) {
@@ -1422,25 +1432,21 @@
     file_flattener_options.update_proguard_spec =
         static_cast<bool>(options_.generate_proguard_rules_path);
 
-    ResourceFileFlattener file_flattener(file_flattener_options, context_,
-                                         keep_set);
+    ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
 
     if (!file_flattener.Flatten(table, writer)) {
-      context_->GetDiagnostics()->Error(DiagMessage()
-                                        << "failed linking file resources");
+      context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
       return false;
     }
 
-    if (options_.static_lib) {
+    if (options_.package_type == PackageType::kStaticLib) {
       if (!FlattenTableToPb(table, writer)) {
-        context_->GetDiagnostics()->Error(
-            DiagMessage() << "failed to write resources.arsc.flat");
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resources.arsc.flat");
         return false;
       }
     } else {
       if (!FlattenTable(table, writer)) {
-        context_->GetDiagnostics()->Error(DiagMessage()
-                                          << "failed to write resources.arsc");
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resources.arsc");
         return false;
       }
     }
@@ -1484,7 +1490,9 @@
 
     context_->SetNameManglerPolicy(
         NameManglerPolicy{context_->GetCompilationPackage()});
-    if (context_->GetCompilationPackage() == "android") {
+    if (options_.package_type == PackageType::kSharedLib) {
+      context_->SetPackageId(0x00);
+    } else if (context_->GetCompilationPackage() == "android") {
       context_->SetPackageId(0x01);
     } else {
       context_->SetPackageId(0x7f);
@@ -1527,7 +1535,7 @@
       return 1;
     }
 
-    if (!options_.static_lib) {
+    if (options_.package_type != PackageType::kStaticLib) {
       PrivateAttributeMover mover;
       if (!mover.Consume(context_, &final_table_)) {
         context_->GetDiagnostics()->Error(
@@ -1538,8 +1546,7 @@
       // Assign IDs if we are building a regular app.
       IdAssigner id_assigner(&options_.stable_id_map);
       if (!id_assigner.Consume(context_, &final_table_)) {
-        context_->GetDiagnostics()->Error(DiagMessage()
-                                          << "failed assigning IDs");
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
         return 1;
       }
 
@@ -1586,17 +1593,15 @@
       return 1;
     }
 
-    if (options_.static_lib) {
+    if (options_.package_type == PackageType::kStaticLib) {
       if (!options_.products.empty()) {
-        context_->GetDiagnostics()
-            ->Warn(DiagMessage()
-                   << "can't select products when building static library");
+        context_->GetDiagnostics()->Warn(DiagMessage()
+                                         << "can't select products when building static library");
       }
     } else {
       ProductFilter product_filter(options_.products);
       if (!product_filter.Consume(context_, &final_table_)) {
-        context_->GetDiagnostics()->Error(DiagMessage()
-                                          << "failed stripping products");
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
         return 1;
       }
     }
@@ -1610,7 +1615,7 @@
       }
     }
 
-    if (!options_.static_lib && context_->GetMinSdkVersion() > 0) {
+    if (options_.package_type != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
       if (context_->IsVerbose()) {
         context_->GetDiagnostics()->Note(
             DiagMessage() << "collapsing resource versions for minimum SDK "
@@ -1626,8 +1631,7 @@
     if (!options_.no_resource_deduping) {
       ResourceDeduper deduper;
       if (!deduper.Consume(context_, &final_table_)) {
-        context_->GetDiagnostics()->Error(DiagMessage()
-                                          << "failed deduping resources");
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
         return 1;
       }
     }
@@ -1635,12 +1639,11 @@
     proguard::KeepSet proguard_keep_set;
     proguard::KeepSet proguard_main_dex_keep_set;
 
-    if (options_.static_lib) {
+    if (options_.package_type == PackageType::kStaticLib) {
       if (options_.table_splitter_options.config_filter != nullptr ||
           !options_.table_splitter_options.preferred_densities.empty()) {
-        context_->GetDiagnostics()
-            ->Warn(DiagMessage()
-                   << "can't strip resources when building static library");
+        context_->GetDiagnostics()->Warn(DiagMessage()
+                                         << "can't strip resources when building static library");
       }
     } else {
       // Adjust the SplitConstraints so that their SDK version is stripped if it
@@ -1774,12 +1777,21 @@
     }
 
     if (options_.generate_java_class_path) {
-      JavaClassGeneratorOptions options;
-      options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
-      options.javadoc_annotations = options_.javadoc_annotations;
+      // The set of packages whose R class to call in the main classes
+      // onResourcesLoaded callback.
+      std::vector<std::string> packages_to_callback;
 
-      if (options_.static_lib || options_.generate_non_final_ids) {
-        options.use_final = false;
+      JavaClassGeneratorOptions template_options;
+      template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
+      template_options.javadoc_annotations = options_.javadoc_annotations;
+
+      if (options_.package_type == PackageType::kStaticLib || options_.generate_non_final_ids) {
+        template_options.use_final = false;
+      }
+
+      if (options_.package_type == PackageType::kSharedLib) {
+        template_options.use_final = false;
+        template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
       }
 
       const StringPiece actual_package = context_->GetCompilationPackage();
@@ -1789,36 +1801,51 @@
         output_package = options_.custom_java_package.value();
       }
 
+      // Generate the private symbols if required.
       if (options_.private_symbols) {
+        packages_to_callback.push_back(options_.private_symbols.value());
+
         // If we defined a private symbols package, we only emit Public symbols
         // to the original package, and private and public symbols to the
         // private package.
-
-        options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
-        if (!WriteJavaFile(&final_table_, context_->GetCompilationPackage(),
-                           output_package, options)) {
-          return 1;
-        }
-
+        JavaClassGeneratorOptions options = template_options;
         options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
-        output_package = options_.private_symbols.value();
-      }
-
-      if (!WriteJavaFile(&final_table_, actual_package, output_package,
-                         options)) {
-        return 1;
-      }
-
-      for (const std::string& extra_package : options_.extra_java_packages) {
-        if (!WriteJavaFile(&final_table_, actual_package, extra_package,
+        if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
                            options)) {
           return 1;
         }
       }
+
+      // Generate all the symbols for all extra packages.
+      for (const std::string& extra_package : options_.extra_java_packages) {
+        packages_to_callback.push_back(extra_package);
+
+        JavaClassGeneratorOptions options = template_options;
+        options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
+        if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
+          return 1;
+        }
+      }
+
+      // Generate the main public R class.
+      JavaClassGeneratorOptions options = template_options;
+
+      // Only generate public symbols if we have a private package.
+      if (options_.private_symbols) {
+        options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
+      }
+
+      if (options.rewrite_callback_options) {
+        options.rewrite_callback_options.value().packages_to_callback =
+            std::move(packages_to_callback);
+      }
+
+      if (!WriteJavaFile(&final_table_, actual_package, output_package, options)) {
+        return 1;
+      }
     }
 
-    if (!WriteProguardFile(options_.generate_proguard_rules_path,
-                           proguard_keep_set)) {
+    if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
       return 1;
     }
 
@@ -1850,9 +1877,11 @@
   std::vector<std::unique_ptr<io::IFileCollection>> collections_;
 
   // A vector of ResourceTables. This is here to retain ownership, so that the
-  // SymbolTable
-  // can use these.
+  // SymbolTable can use these.
   std::vector<std::unique_ptr<ResourceTable>> static_table_includes_;
+
+  // The set of shared libraries being used, mapping their assigned package ID to package name.
+  std::map<size_t, std::string> shared_libs_;
 };
 
 int Link(const std::vector<StringPiece>& args) {
@@ -1866,6 +1895,8 @@
   bool legacy_x_flag = false;
   bool require_localization = false;
   bool verbose = false;
+  bool shared_lib = false;
+  bool static_lib = false;
   Maybe<std::string> stable_id_file_path;
   std::vector<std::string> split_args;
   Flags flags =
@@ -1942,7 +1973,8 @@
                         "Version name to inject into the AndroidManifest.xml "
                         "if none is present",
                         &options.manifest_fixer_options.version_name_default)
-          .OptionalSwitch("--static-lib", "Generate a static Android library", &options.static_lib)
+          .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library", &shared_lib)
+          .OptionalSwitch("--static-lib", "Generate a static Android library", &static_lib)
           .OptionalSwitch("--no-static-lib-packages",
                           "Merge all library resources under the app's package",
                           &options.no_static_lib_packages)
@@ -2096,7 +2128,19 @@
     options.table_splitter_options.preferred_densities.push_back(preferred_density_config.density);
   }
 
-  if (!options.static_lib && stable_id_file_path) {
+  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)) {
       return 1;
@@ -2122,7 +2166,7 @@
   }
 
   // Turn off auto versioning for static-libs.
-  if (options.static_lib) {
+  if (options.package_type == PackageType::kStaticLib) {
     options.no_auto_version = true;
     options.no_version_vectors = true;
     options.no_version_transitions = true;
diff --git a/tools/aapt2/link/Linkers.h b/tools/aapt2/link/Linkers.h
index 4687d2c..d00fa73 100644
--- a/tools/aapt2/link/Linkers.h
+++ b/tools/aapt2/link/Linkers.h
@@ -58,29 +58,6 @@
   DISALLOW_COPY_AND_ASSIGN(AutoVersioner);
 };
 
-class VersionCollapser : public IResourceTableConsumer {
- public:
-  VersionCollapser() = default;
-
-  bool Consume(IAaptContext* context, ResourceTable* table) override;
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(VersionCollapser);
-};
-
-/**
- * Removes duplicated key-value entries from dominated resources.
- */
-class ResourceDeduper : public IResourceTableConsumer {
- public:
-  ResourceDeduper() = default;
-
-  bool Consume(IAaptContext* context, ResourceTable* table) override;
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(ResourceDeduper);
-};
-
 /**
  * If any attribute resource values are defined as public, this consumer will
  * move all private
diff --git a/tools/aapt2/link/ManifestFixer.cpp b/tools/aapt2/link/ManifestFixer.cpp
index b4cf4f8..313fe45 100644
--- a/tools/aapt2/link/ManifestFixer.cpp
+++ b/tools/aapt2/link/ManifestFixer.cpp
@@ -54,16 +54,14 @@
   return true;
 }
 
-static bool OptionalNameIsJavaClassName(xml::Element* el,
-                                        SourcePathDiagnostics* diag) {
+static bool OptionalNameIsJavaClassName(xml::Element* el, SourcePathDiagnostics* diag) {
   if (xml::Attribute* attr = el->FindAttribute(xml::kSchemaAndroid, "name")) {
     return NameIsJavaClassName(el, attr, diag);
   }
   return true;
 }
 
-static bool RequiredNameIsJavaClassName(xml::Element* el,
-                                        SourcePathDiagnostics* diag) {
+static bool RequiredNameIsJavaClassName(xml::Element* el, SourcePathDiagnostics* diag) {
   if (xml::Attribute* attr = el->FindAttribute(xml::kSchemaAndroid, "name")) {
     return NameIsJavaClassName(el, attr, diag);
   }
@@ -72,6 +70,26 @@
   return false;
 }
 
+static bool RequiredNameIsJavaPackage(xml::Element* el, SourcePathDiagnostics* diag) {
+  if (xml::Attribute* attr = el->FindAttribute(xml::kSchemaAndroid, "name")) {
+    return util::IsJavaPackageName(attr->value);
+  }
+  diag->Error(DiagMessage(el->line_number)
+              << "<" << el->name << "> is missing attribute 'android:name'");
+  return false;
+}
+
+static xml::XmlNodeAction::ActionFuncWithDiag RequiredAndroidAttribute(const std::string& attr) {
+  return [=](xml::Element* el, SourcePathDiagnostics* diag) -> bool {
+    if (el->FindAttribute(xml::kSchemaAndroid, attr) == nullptr) {
+      diag->Error(DiagMessage(el->line_number)
+                  << "<" << el->name << "> is missing required attribute 'android:" << attr << "'");
+      return false;
+    }
+    return true;
+  };
+}
+
 static bool VerifyManifest(xml::Element* el, SourcePathDiagnostics* diag) {
   xml::Attribute* attr = el->FindAttribute({}, "package");
   if (!attr) {
@@ -263,7 +281,18 @@
   xml::XmlNodeAction& application_action = manifest_action["application"];
   application_action.Action(OptionalNameIsJavaClassName);
 
-  application_action["uses-library"];
+  application_action["uses-library"].Action(RequiredNameIsJavaPackage);
+  application_action["library"].Action(RequiredNameIsJavaPackage);
+
+  xml::XmlNodeAction& static_library_action = application_action["static-library"];
+  static_library_action.Action(RequiredNameIsJavaPackage);
+  static_library_action.Action(RequiredAndroidAttribute("version"));
+
+  xml::XmlNodeAction& uses_static_library_action = application_action["uses-static-library"];
+  uses_static_library_action.Action(RequiredNameIsJavaPackage);
+  uses_static_library_action.Action(RequiredAndroidAttribute("version"));
+  uses_static_library_action.Action(RequiredAndroidAttribute("certDigest"));
+
   application_action["meta-data"] = meta_data_action;
   application_action["activity"] = component_action;
   application_action["activity-alias"] = component_action;
diff --git a/tools/aapt2/link/PrivateAttributeMover.cpp b/tools/aapt2/link/PrivateAttributeMover.cpp
index cc07a6e..eee4b60 100644
--- a/tools/aapt2/link/PrivateAttributeMover.cpp
+++ b/tools/aapt2/link/PrivateAttributeMover.cpp
@@ -26,11 +26,9 @@
 namespace aapt {
 
 template <typename InputContainer, typename OutputIterator, typename Predicate>
-OutputIterator move_if(InputContainer& input_container, OutputIterator result,
-                       Predicate pred) {
+OutputIterator move_if(InputContainer& input_container, OutputIterator result, Predicate pred) {
   const auto last = input_container.end();
-  auto new_end =
-      std::find_if(input_container.begin(), input_container.end(), pred);
+  auto new_end = std::find_if(input_container.begin(), input_container.end(), pred);
   if (new_end == last) {
     return result;
   }
@@ -57,8 +55,7 @@
   return result;
 }
 
-bool PrivateAttributeMover::Consume(IAaptContext* context,
-                                    ResourceTable* table) {
+bool PrivateAttributeMover::Consume(IAaptContext* context, ResourceTable* table) {
   for (auto& package : table->packages) {
     ResourceTableType* type = package->FindType(ResourceType::kAttr);
     if (!type) {
@@ -68,18 +65,24 @@
     if (type->symbol_status.state != SymbolState::kPublic) {
       // No public attributes, so we can safely leave these private attributes
       // where they are.
-      return true;
+      continue;
     }
 
-    ResourceTableType* priv_attr_type =
-        package->FindOrCreateType(ResourceType::kAttrPrivate);
-    CHECK(priv_attr_type->entries.empty());
+    std::vector<std::unique_ptr<ResourceEntry>> private_attr_entries;
 
-    move_if(type->entries, std::back_inserter(priv_attr_type->entries),
+    move_if(type->entries, std::back_inserter(private_attr_entries),
             [](const std::unique_ptr<ResourceEntry>& entry) -> bool {
               return entry->symbol_status.state != SymbolState::kPublic;
             });
-    break;
+
+    if (private_attr_entries.empty()) {
+      // No private attributes.
+      continue;
+    }
+
+    ResourceTableType* priv_attr_type = package->FindOrCreateType(ResourceType::kAttrPrivate);
+    CHECK(priv_attr_type->entries.empty());
+    priv_attr_type->entries = std::move(private_attr_entries);
   }
   return true;
 }
diff --git a/tools/aapt2/link/PrivateAttributeMover_test.cpp b/tools/aapt2/link/PrivateAttributeMover_test.cpp
index 90c4922..7fcf6e7 100644
--- a/tools/aapt2/link/PrivateAttributeMover_test.cpp
+++ b/tools/aapt2/link/PrivateAttributeMover_test.cpp
@@ -54,8 +54,7 @@
   EXPECT_NE(type->FindEntry("privateB"), nullptr);
 }
 
-TEST(PrivateAttributeMoverTest,
-     LeavePrivateAttributesWhenNoPublicAttributesDefined) {
+TEST(PrivateAttributeMoverTest, LeavePrivateAttributesWhenNoPublicAttributesDefined) {
   std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
 
   std::unique_ptr<ResourceTable> table = test::ResourceTableBuilder()
@@ -77,4 +76,23 @@
   ASSERT_EQ(type, nullptr);
 }
 
+TEST(PrivateAttributeMoverTest, DoNotCreatePrivateAttrsIfNoneExist) {
+  std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
+  std::unique_ptr<ResourceTable> table =
+      test::ResourceTableBuilder()
+          .AddSimple("android:attr/pub")
+          .SetSymbolState("android:attr/pub", ResourceId(0x01010000), SymbolState::kPublic)
+          .Build();
+
+  ResourceTablePackage* package = table->FindPackage("android");
+  ASSERT_NE(nullptr, package);
+
+  ASSERT_EQ(nullptr, package->FindType(ResourceType::kAttrPrivate));
+
+  PrivateAttributeMover mover;
+  ASSERT_TRUE(mover.Consume(context.get(), table.get()));
+
+  ASSERT_EQ(nullptr, package->FindType(ResourceType::kAttrPrivate));
+}
+
 }  // namespace aapt
diff --git a/tools/aapt2/link/ReferenceLinker.cpp b/tools/aapt2/link/ReferenceLinker.cpp
index ea68b61..0331313 100644
--- a/tools/aapt2/link/ReferenceLinker.cpp
+++ b/tools/aapt2/link/ReferenceLinker.cpp
@@ -96,10 +96,8 @@
 
       // Find the attribute in the symbol table and check if it is visible from
       // this callsite.
-      const SymbolTable::Symbol* symbol =
-          ReferenceLinker::ResolveAttributeCheckVisibility(
-              transformed_reference, context_->GetNameMangler(), symbols_,
-              callsite_, &err_str);
+      const SymbolTable::Symbol* symbol = ReferenceLinker::ResolveAttributeCheckVisibility(
+          transformed_reference, symbols_, callsite_, &err_str);
       if (symbol) {
         // Assign our style key the correct ID.
         // The ID may not exist.
@@ -124,8 +122,7 @@
           DiagMessage msg(entry.key.GetSource());
 
           // Call the matches method again, this time with a DiagMessage so we
-          // fill
-          // in the actual error message.
+          // fill in the actual error message.
           symbol->attribute->Matches(entry.value.get(), &msg);
           context_->GetDiagnostics()->Error(msg);
           error_ = true;
@@ -225,12 +222,10 @@
   return true;
 }
 
-const SymbolTable::Symbol* ReferenceLinker::ResolveSymbol(
-    const Reference& reference, NameMangler* mangler, SymbolTable* symbols) {
+const SymbolTable::Symbol* ReferenceLinker::ResolveSymbol(const Reference& reference,
+                                                          SymbolTable* symbols) {
   if (reference.name) {
-    Maybe<ResourceName> mangled = mangler->MangleName(reference.name.value());
-    return symbols->FindByName(mangled ? mangled.value()
-                                       : reference.name.value());
+    return symbols->FindByName(reference.name.value());
   } else if (reference.id) {
     return symbols->FindById(reference.id.value());
   } else {
@@ -238,11 +233,11 @@
   }
 }
 
-const SymbolTable::Symbol* ReferenceLinker::ResolveSymbolCheckVisibility(
-    const Reference& reference, NameMangler* name_mangler, SymbolTable* symbols,
-    CallSite* callsite, std::string* out_error) {
-  const SymbolTable::Symbol* symbol =
-      ResolveSymbol(reference, name_mangler, symbols);
+const SymbolTable::Symbol* ReferenceLinker::ResolveSymbolCheckVisibility(const Reference& reference,
+                                                                         SymbolTable* symbols,
+                                                                         CallSite* callsite,
+                                                                         std::string* out_error) {
+  const SymbolTable::Symbol* symbol = ResolveSymbol(reference, symbols);
   if (!symbol) {
     if (out_error) *out_error = "not found";
     return nullptr;
@@ -256,10 +251,9 @@
 }
 
 const SymbolTable::Symbol* ReferenceLinker::ResolveAttributeCheckVisibility(
-    const Reference& reference, NameMangler* name_mangler, SymbolTable* symbols,
-    CallSite* callsite, std::string* out_error) {
-  const SymbolTable::Symbol* symbol = ResolveSymbolCheckVisibility(
-      reference, name_mangler, symbols, callsite, out_error);
+    const Reference& reference, SymbolTable* symbols, CallSite* callsite, std::string* out_error) {
+  const SymbolTable::Symbol* symbol =
+      ResolveSymbolCheckVisibility(reference, symbols, callsite, out_error);
   if (!symbol) {
     return nullptr;
   }
@@ -271,11 +265,11 @@
   return symbol;
 }
 
-Maybe<xml::AaptAttribute> ReferenceLinker::CompileXmlAttribute(
-    const Reference& reference, NameMangler* name_mangler, SymbolTable* symbols,
-    CallSite* callsite, std::string* out_error) {
-  const SymbolTable::Symbol* symbol =
-      ResolveSymbol(reference, name_mangler, symbols);
+Maybe<xml::AaptAttribute> ReferenceLinker::CompileXmlAttribute(const Reference& reference,
+                                                               SymbolTable* symbols,
+                                                               CallSite* callsite,
+                                                               std::string* out_error) {
+  const SymbolTable::Symbol* symbol = ResolveSymbol(reference, symbols);
   if (!symbol) {
     if (out_error) *out_error = "not found";
     return {};
@@ -311,13 +305,11 @@
   CHECK(reference->name || reference->id);
 
   Reference transformed_reference = *reference;
-  TransformReferenceFromNamespace(decls, context->GetCompilationPackage(),
-                                  &transformed_reference);
+  TransformReferenceFromNamespace(decls, context->GetCompilationPackage(), &transformed_reference);
 
   std::string err_str;
-  const SymbolTable::Symbol* s = ResolveSymbolCheckVisibility(
-      transformed_reference, context->GetNameMangler(), symbols, callsite,
-      &err_str);
+  const SymbolTable::Symbol* s =
+      ResolveSymbolCheckVisibility(transformed_reference, symbols, callsite, &err_str);
   if (s) {
     // The ID may not exist. This is fine because of the possibility of building
     // against libraries without assigned IDs.
diff --git a/tools/aapt2/link/ReferenceLinker.h b/tools/aapt2/link/ReferenceLinker.h
index bdabf24..2d18c49 100644
--- a/tools/aapt2/link/ReferenceLinker.h
+++ b/tools/aapt2/link/ReferenceLinker.h
@@ -51,18 +51,17 @@
    * Performs name mangling and looks up the resource in the symbol table.
    * Returns nullptr if the symbol was not found.
    */
-  static const SymbolTable::Symbol* ResolveSymbol(const Reference& reference,
-                                                  NameMangler* mangler,
-                                                  SymbolTable* symbols);
+  static const SymbolTable::Symbol* ResolveSymbol(const Reference& reference, SymbolTable* symbols);
 
   /**
    * Performs name mangling and looks up the resource in the symbol table. If
    * the symbol is not visible by the reference at the callsite, nullptr is
    * returned. out_error holds the error message.
    */
-  static const SymbolTable::Symbol* ResolveSymbolCheckVisibility(
-      const Reference& reference, NameMangler* name_mangler,
-      SymbolTable* symbols, CallSite* callsite, std::string* out_error);
+  static const SymbolTable::Symbol* ResolveSymbolCheckVisibility(const Reference& reference,
+                                                                 SymbolTable* symbols,
+                                                                 CallSite* callsite,
+                                                                 std::string* out_error);
 
   /**
    * Same as resolveSymbolCheckVisibility(), but also makes sure the symbol is
@@ -70,18 +69,19 @@
    * That is, the return value will have a non-null value for
    * ISymbolTable::Symbol::attribute.
    */
-  static const SymbolTable::Symbol* ResolveAttributeCheckVisibility(
-      const Reference& reference, NameMangler* name_mangler,
-      SymbolTable* symbols, CallSite* callsite, std::string* out_error);
+  static const SymbolTable::Symbol* ResolveAttributeCheckVisibility(const Reference& reference,
+                                                                    SymbolTable* symbols,
+                                                                    CallSite* callsite,
+                                                                    std::string* out_error);
 
   /**
    * Resolves the attribute reference and returns an xml::AaptAttribute if
    * successful.
    * If resolution fails, outError holds the error message.
    */
-  static Maybe<xml::AaptAttribute> CompileXmlAttribute(
-      const Reference& reference, NameMangler* name_mangler,
-      SymbolTable* symbols, CallSite* callsite, std::string* out_error);
+  static Maybe<xml::AaptAttribute> CompileXmlAttribute(const Reference& reference,
+                                                       SymbolTable* symbols, CallSite* callsite,
+                                                       std::string* out_error);
 
   /**
    * Writes the resource name to the DiagMessage, using the
diff --git a/tools/aapt2/link/TableMerger.cpp b/tools/aapt2/link/TableMerger.cpp
index 7e7b9fb..9311091 100644
--- a/tools/aapt2/link/TableMerger.cpp
+++ b/tools/aapt2/link/TableMerger.cpp
@@ -39,14 +39,12 @@
 
 bool TableMerger::Merge(const Source& src, ResourceTable* table,
                         io::IFileCollection* collection) {
-  return MergeImpl(src, table, collection, false /* overlay */,
-                   true /* allow new */);
+  return MergeImpl(src, table, collection, false /* overlay */, true /* allow new */);
 }
 
 bool TableMerger::MergeOverlay(const Source& src, ResourceTable* table,
                                io::IFileCollection* collection) {
-  return MergeImpl(src, table, collection, true /* overlay */,
-                   options_.auto_add_overlay);
+  return MergeImpl(src, table, collection, true /* overlay */, options_.auto_add_overlay);
 }
 
 /**
@@ -55,25 +53,13 @@
 bool TableMerger::MergeImpl(const Source& src, ResourceTable* table,
                             io::IFileCollection* collection, bool overlay,
                             bool allow_new) {
-  const uint8_t desired_package_id = context_->GetPackageId();
-
   bool error = false;
   for (auto& package : table->packages) {
-    // Warn of packages with an unrelated ID.
-    const Maybe<ResourceId>& id = package->id;
-    if (id && id.value() != 0x0 && id.value() != desired_package_id) {
-      context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring package "
-                                                        << package->name);
-      continue;
-    }
-
     // Only merge an empty package or the package we're building.
     // Other packages may exist, which likely contain attribute definitions.
     // This is because at compile time it is unknown if the attributes are
-    // simply
-    // uses of the attribute or definitions.
-    if (package->name.empty() ||
-        context_->GetCompilationPackage() == package->name) {
+    // simply uses of the attribute or definitions.
+    if (package->name.empty() || context_->GetCompilationPackage() == package->name) {
       FileMergeCallback callback;
       if (collection) {
         callback = [&](const ResourceNameRef& name,
@@ -83,8 +69,7 @@
           io::IFile* f = collection->FindFile(*old_file->path);
           if (!f) {
             context_->GetDiagnostics()->Error(DiagMessage(src)
-                                              << "file '" << *old_file->path
-                                              << "' not found");
+                                              << "file '" << *old_file->path << "' not found");
             return false;
           }
 
diff --git a/tools/aapt2/link/XmlReferenceLinker.cpp b/tools/aapt2/link/XmlReferenceLinker.cpp
index 1dbe53c..b839862 100644
--- a/tools/aapt2/link/XmlReferenceLinker.cpp
+++ b/tools/aapt2/link/XmlReferenceLinker.cpp
@@ -107,8 +107,8 @@
         attr_ref.private_reference = maybe_package.value().private_namespace;
 
         std::string err_str;
-        attr.compiled_attribute = ReferenceLinker::CompileXmlAttribute(
-            attr_ref, context_->GetNameMangler(), symbols_, callsite_, &err_str);
+        attr.compiled_attribute =
+            ReferenceLinker::CompileXmlAttribute(attr_ref, symbols_, callsite_, &err_str);
 
         if (!attr.compiled_attribute) {
           context_->GetDiagnostics()->Error(DiagMessage(source) << "attribute '"
diff --git a/tools/aapt2/optimize/Optimize.cpp b/tools/aapt2/optimize/Optimize.cpp
new file mode 100644
index 0000000..9615962
--- /dev/null
+++ b/tools/aapt2/optimize/Optimize.cpp
@@ -0,0 +1,201 @@
+/*
+ * 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.
+ */
+
+#include <memory>
+#include <vector>
+
+#include "androidfw/StringPiece.h"
+
+#include "Diagnostics.h"
+#include "Flags.h"
+#include "LoadedApk.h"
+#include "SdkConstants.h"
+#include "flatten/TableFlattener.h"
+#include "optimize/ResourceDeduper.h"
+#include "optimize/VersionCollapser.h"
+#include "split/TableSplitter.h"
+
+using android::StringPiece;
+
+namespace aapt {
+
+struct OptimizeOptions {
+  // Path to the output APK.
+  std::string output_path;
+
+  // List of screen density configurations the APK will be optimized for.
+  std::vector<ConfigDescription> target_configs;
+
+  TableFlattenerOptions table_flattener_options;
+};
+
+class OptimizeContext : public IAaptContext {
+ public:
+  IDiagnostics* GetDiagnostics() override { return &diagnostics_; }
+
+  NameMangler* GetNameMangler() override {
+    abort();
+    return nullptr;
+  }
+
+  const std::string& GetCompilationPackage() override {
+    static std::string empty;
+    return empty;
+  }
+
+  uint8_t GetPackageId() override { return 0; }
+
+  SymbolTable* GetExternalSymbols() override {
+    abort();
+    return nullptr;
+  }
+
+  bool IsVerbose() override { return verbose_; }
+
+  void SetVerbose(bool val) { verbose_ = val; }
+
+  void SetMinSdkVersion(int sdk_version) { sdk_version_ = sdk_version; }
+
+  int GetMinSdkVersion() override { return sdk_version_; }
+
+ private:
+  StdErrDiagnostics diagnostics_;
+  bool verbose_ = false;
+  int sdk_version_ = 0;
+};
+
+class OptimizeCommand {
+ public:
+  OptimizeCommand(OptimizeContext* context, const OptimizeOptions& options)
+      : options_(options),
+        context_(context) {}
+
+  int Run(std::unique_ptr<LoadedApk> apk) {
+    if (context_->IsVerbose()) {
+      context_->GetDiagnostics()->Note(DiagMessage() << "Optimizing APK...");
+    }
+
+    VersionCollapser collapser;
+    if (!collapser.Consume(context_, apk->GetResourceTable())) {
+      return 1;
+    }
+
+    ResourceDeduper deduper;
+    if (!deduper.Consume(context_, apk->GetResourceTable())) {
+      context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
+      return 1;
+    }
+
+    // Stripping the APK using the TableSplitter with no splits and the target
+    // densities as the preferred densities. The resource table is modified in
+    // place in the LoadedApk.
+    TableSplitterOptions splitter_options;
+    for (auto& config : options_.target_configs) {
+      splitter_options.preferred_densities.push_back(config.density);
+    }
+    std::vector<SplitConstraints> splits;
+    TableSplitter splitter(splits, splitter_options);
+    splitter.SplitTable(apk->GetResourceTable());
+
+    std::unique_ptr<IArchiveWriter> writer =
+        CreateZipFileArchiveWriter(context_->GetDiagnostics(), options_.output_path);
+    if (!apk->WriteToArchive(context_, options_.table_flattener_options, writer.get())) {
+      return 1;
+    }
+
+    return 0;
+  }
+
+ private:
+  OptimizeOptions options_;
+  OptimizeContext* context_;
+};
+
+int Optimize(const std::vector<StringPiece>& args) {
+  OptimizeContext context;
+  OptimizeOptions options;
+  Maybe<std::string> target_densities;
+  bool verbose = false;
+  Flags flags =
+      Flags()
+          .RequiredFlag("-o", "Path to the output APK.", &options.output_path)
+          .OptionalFlag(
+              "--target-densities",
+              "Comma separated list of the screen densities that the APK will "
+              "be optimized for. All the resources that would be unused on "
+              "devices of the given densities will be removed from the APK.",
+              &target_densities)
+          .OptionalSwitch("--enable-sparse-encoding",
+                          "Enables encoding sparse entries using a binary search tree.\n"
+                          "This decreases APK size at the cost of resource retrieval performance.",
+                          &options.table_flattener_options.use_sparse_entries)
+          .OptionalSwitch("-v", "Enables verbose logging", &verbose);
+
+  if (!flags.Parse("aapt2 optimize", args, &std::cerr)) {
+    return 1;
+  }
+
+  if (flags.GetArgs().size() != 1u) {
+    std::cerr << "must have one APK as argument.\n\n";
+    flags.Usage("aapt2 optimize", &std::cerr);
+    return 1;
+  }
+
+  std::unique_ptr<LoadedApk> apk =
+      LoadedApk::LoadApkFromPath(&context, flags.GetArgs()[0]);
+  if (!apk) {
+    return 1;
+  }
+
+  if (verbose) {
+    context.SetVerbose(verbose);
+  }
+
+  if (target_densities) {
+    // Parse the target screen densities.
+    for (const StringPiece& config_str : util::Tokenize(target_densities.value(), ',')) {
+      ConfigDescription config;
+      if (!ConfigDescription::Parse(config_str, &config) || config.density == 0) {
+        context.GetDiagnostics()->Error(
+            DiagMessage() << "invalid density '" << config_str
+                          << "' for --target-densities option");
+        return 1;
+      }
+
+      // Clear the version that can be automatically added.
+      config.sdkVersion = 0;
+
+      if (config.diff(ConfigDescription::DefaultConfig()) !=
+          ConfigDescription::CONFIG_DENSITY) {
+        context.GetDiagnostics()->Error(
+            DiagMessage() << "invalid density '" << config_str
+                          << "' for --target-densities option. Must be only a "
+                          << "density value.");
+        return 1;
+      }
+
+      options.target_configs.push_back(config);
+    }
+  }
+
+  // TODO(adamlesinski): Read manfiest and set the proper minSdkVersion.
+  // context.SetMinSdkVersion(SDK_O);
+
+  OptimizeCommand cmd(&context, options);
+  return cmd.Run(std::move(apk));
+}
+
+}  // namespace aapt
diff --git a/tools/aapt2/link/ResourceDeduper.cpp b/tools/aapt2/optimize/ResourceDeduper.cpp
similarity index 98%
rename from tools/aapt2/link/ResourceDeduper.cpp
rename to tools/aapt2/optimize/ResourceDeduper.cpp
index 9431dce..3aab2e3 100644
--- a/tools/aapt2/link/ResourceDeduper.cpp
+++ b/tools/aapt2/optimize/ResourceDeduper.cpp
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#include "link/Linkers.h"
+#include "optimize/ResourceDeduper.h"
 
 #include <algorithm>
 
diff --git a/tools/aapt2/optimize/ResourceDeduper.h b/tools/aapt2/optimize/ResourceDeduper.h
new file mode 100644
index 0000000..4a669d4
--- /dev/null
+++ b/tools/aapt2/optimize/ResourceDeduper.h
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+
+#ifndef AAPT_OPTIMIZE_RESOURCEDEDUPER_H
+#define AAPT_OPTIMIZE_RESOURCEDEDUPER_H
+
+#include "android-base/macros.h"
+
+#include "process/IResourceTableConsumer.h"
+
+namespace aapt {
+
+class ResourceTable;
+
+// Removes duplicated key-value entries from dominated resources.
+class ResourceDeduper : public IResourceTableConsumer {
+ public:
+  ResourceDeduper() = default;
+
+  bool Consume(IAaptContext* context, ResourceTable* table) override;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(ResourceDeduper);
+};
+
+} // namespace aapt
+
+#endif  // AAPT_OPTIMIZE_RESOURCEDEDUPER_H
diff --git a/tools/aapt2/link/ResourceDeduper_test.cpp b/tools/aapt2/optimize/ResourceDeduper_test.cpp
similarity index 98%
rename from tools/aapt2/link/ResourceDeduper_test.cpp
rename to tools/aapt2/optimize/ResourceDeduper_test.cpp
index d38059d..4d00fa6 100644
--- a/tools/aapt2/link/ResourceDeduper_test.cpp
+++ b/tools/aapt2/optimize/ResourceDeduper_test.cpp
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#include "link/Linkers.h"
+#include "optimize/ResourceDeduper.h"
 
 #include "ResourceTable.h"
 #include "test/Test.h"
diff --git a/tools/aapt2/link/VersionCollapser.cpp b/tools/aapt2/optimize/VersionCollapser.cpp
similarity index 98%
rename from tools/aapt2/link/VersionCollapser.cpp
rename to tools/aapt2/optimize/VersionCollapser.cpp
index 3df5899..d941b48 100644
--- a/tools/aapt2/link/VersionCollapser.cpp
+++ b/tools/aapt2/optimize/VersionCollapser.cpp
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#include "link/Linkers.h"
+#include "optimize/VersionCollapser.h"
 
 #include <algorithm>
 #include <vector>
diff --git a/tools/aapt2/optimize/VersionCollapser.h b/tools/aapt2/optimize/VersionCollapser.h
new file mode 100644
index 0000000..5ab3b25
--- /dev/null
+++ b/tools/aapt2/optimize/VersionCollapser.h
@@ -0,0 +1,40 @@
+/*
+ * 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.
+ */
+
+#ifndef AAPT_OPTIMIZE_VERSIONCOLLAPSER_H
+#define AAPT_OPTIMIZE_VERSIONCOLLAPSER_H
+
+#include "android-base/macros.h"
+
+#include "process/IResourceTableConsumer.h"
+
+namespace aapt {
+
+class ResourceTable;
+
+class VersionCollapser : public IResourceTableConsumer {
+ public:
+  VersionCollapser() = default;
+
+  bool Consume(IAaptContext* context, ResourceTable* table) override;
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(VersionCollapser);
+};
+
+} // namespace aapt
+
+#endif  // AAPT_OPTIMIZE_VERSIONCOLLAPSER_H
diff --git a/tools/aapt2/link/VersionCollapser_test.cpp b/tools/aapt2/optimize/VersionCollapser_test.cpp
similarity index 98%
rename from tools/aapt2/link/VersionCollapser_test.cpp
rename to tools/aapt2/optimize/VersionCollapser_test.cpp
index 44babb2..aa0d0c0 100644
--- a/tools/aapt2/link/VersionCollapser_test.cpp
+++ b/tools/aapt2/optimize/VersionCollapser_test.cpp
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#include "link/Linkers.h"
+#include "optimize/VersionCollapser.h"
 
 #include "test/Test.h"
 
diff --git a/tools/aapt2/process/SymbolTable.cpp b/tools/aapt2/process/SymbolTable.cpp
index 1a3da73..bcafbca 100644
--- a/tools/aapt2/process/SymbolTable.cpp
+++ b/tools/aapt2/process/SymbolTable.cpp
@@ -16,10 +16,15 @@
 
 #include "process/SymbolTable.h"
 
+#include <iostream>
+
+#include "android-base/logging.h"
+#include "android-base/stringprintf.h"
 #include "androidfw/AssetManager.h"
 #include "androidfw/ResourceTypes.h"
 
 #include "ConfigDescription.h"
+#include "NameMangler.h"
 #include "Resource.h"
 #include "ResourceUtils.h"
 #include "ValueVisitor.h"
@@ -45,25 +50,49 @@
 }
 
 const SymbolTable::Symbol* SymbolTable::FindByName(const ResourceName& name) {
-  if (const std::shared_ptr<Symbol>& s = cache_.get(name)) {
+  const ResourceName* name_with_package = &name;
+
+  // Fill in the package name if necessary.
+  // If there is no package in `name`, we will need to copy the ResourceName
+  // and store it somewhere; we use the Maybe<> class to reserve storage.
+  Maybe<ResourceName> name_with_package_impl;
+  if (name.package.empty()) {
+    name_with_package_impl = ResourceName(mangler_->GetTargetPackageName(), name.type, name.entry);
+    name_with_package = &name_with_package_impl.value();
+  }
+
+  // We store the name unmangled in the cache, so look it up as-is.
+  if (const std::shared_ptr<Symbol>& s = cache_.get(*name_with_package)) {
     return s.get();
   }
 
-  // We did not find it in the cache, so look through the sources.
+  // The name was not found in the cache. Mangle it (if necessary) and find it in our sources.
+  // Again, here we use a Maybe<> object to reserve storage if we need to mangle.
+  const ResourceName* mangled_name = name_with_package;
+  Maybe<ResourceName> mangled_name_impl;
+  if (mangler_->ShouldMangle(name_with_package->package)) {
+    mangled_name_impl = mangler_->MangleName(*name_with_package);
+    mangled_name = &mangled_name_impl.value();
+  }
+
   for (auto& symbolSource : sources_) {
-    std::unique_ptr<Symbol> symbol = symbolSource->FindByName(name);
+    std::unique_ptr<Symbol> symbol = symbolSource->FindByName(*mangled_name);
     if (symbol) {
       // Take ownership of the symbol into a shared_ptr. We do this because
-      // LruCache
-      // doesn't support unique_ptr.
-      std::shared_ptr<Symbol> shared_symbol =
-          std::shared_ptr<Symbol>(symbol.release());
-      cache_.put(name, shared_symbol);
+      // LruCache doesn't support unique_ptr.
+      std::shared_ptr<Symbol> shared_symbol(std::move(symbol));
+
+      // Since we look in the cache with the unmangled, but package prefixed
+      // name, we must put the same name into the cache.
+      cache_.put(*name_with_package, shared_symbol);
 
       if (shared_symbol->id) {
         // The symbol has an ID, so we can also cache this!
         id_cache_.put(shared_symbol->id.value(), shared_symbol);
       }
+
+      // Returns the raw pointer. Callers are not expected to hold on to this
+      // between calls to Find*.
       return shared_symbol.get();
     }
   }
@@ -79,12 +108,13 @@
   for (auto& symbolSource : sources_) {
     std::unique_ptr<Symbol> symbol = symbolSource->FindById(id);
     if (symbol) {
-      // Take ownership of the symbol into a shared_ptr. We do this because
-      // LruCache
+      // Take ownership of the symbol into a shared_ptr. We do this because LruCache
       // doesn't support unique_ptr.
-      std::shared_ptr<Symbol> shared_symbol =
-          std::shared_ptr<Symbol>(symbol.release());
+      std::shared_ptr<Symbol> shared_symbol(std::move(symbol));
       id_cache_.put(id, shared_symbol);
+
+      // Returns the raw pointer. Callers are not expected to hold on to this
+      // between calls to Find*.
       return shared_symbol.get();
     }
   }
@@ -92,16 +122,12 @@
 }
 
 const SymbolTable::Symbol* SymbolTable::FindByReference(const Reference& ref) {
-  // First try the ID. This is because when we lookup by ID, we only fill in the
-  // ID cache.
-  // Looking up by name fills in the name and ID cache. So a cache miss will
-  // cause a failed
-  // ID lookup, then a successful name lookup. Subsequent look ups will hit
-  // immediately
+  // First try the ID. This is because when we lookup by ID, we only fill in the ID cache.
+  // Looking up by name fills in the name and ID cache. So a cache miss will cause a failed
+  // ID lookup, then a successful name lookup. Subsequent look ups will hit immediately
   // because the ID is cached too.
   //
-  // If we looked up by name first, a cache miss would mean we failed to lookup
-  // by name, then
+  // If we looked up by name first, a cache miss would mean we failed to lookup by name, then
   // succeeded to lookup by ID. Subsequent lookups will miss then hit.
   const SymbolTable::Symbol* symbol = nullptr;
   if (ref.id) {
@@ -120,25 +146,21 @@
   if (!result) {
     if (name.type == ResourceType::kAttr) {
       // Recurse and try looking up a private attribute.
-      return FindByName(
-          ResourceName(name.package, ResourceType::kAttrPrivate, name.entry));
+      return FindByName(ResourceName(name.package, ResourceType::kAttrPrivate, name.entry));
     }
     return {};
   }
 
   ResourceTable::SearchResult sr = result.value();
 
-  std::unique_ptr<SymbolTable::Symbol> symbol =
-      util::make_unique<SymbolTable::Symbol>();
+  std::unique_ptr<SymbolTable::Symbol> symbol = util::make_unique<SymbolTable::Symbol>();
   symbol->is_public = (sr.entry->symbol_status.state == SymbolState::kPublic);
 
   if (sr.package->id && sr.type->id && sr.entry->id) {
-    symbol->id = ResourceId(sr.package->id.value(), sr.type->id.value(),
-                            sr.entry->id.value());
+    symbol->id = ResourceId(sr.package->id.value(), sr.type->id.value(), sr.entry->id.value());
   }
 
-  if (name.type == ResourceType::kAttr ||
-      name.type == ResourceType::kAttrPrivate) {
+  if (name.type == ResourceType::kAttr || name.type == ResourceType::kAttrPrivate) {
     const ConfigDescription kDefaultConfig;
     ResourceConfigValue* config_value = sr.entry->FindValue(kDefaultConfig);
     if (config_value) {
@@ -155,8 +177,18 @@
 
 bool AssetManagerSymbolSource::AddAssetPath(const StringPiece& path) {
   int32_t cookie = 0;
-  return assets_.addAssetPath(android::String8(path.data(), path.size()),
-                              &cookie);
+  return assets_.addAssetPath(android::String8(path.data(), path.size()), &cookie);
+}
+
+std::map<size_t, std::string> AssetManagerSymbolSource::GetAssignedPackageIds() const {
+  std::map<size_t, std::string> package_map;
+  const android::ResTable& table = assets_.getResources(false);
+  const size_t package_count = table.getBasePackageCount();
+  for (size_t i = 0; i < package_count; i++) {
+    package_map[table.getBasePackageId(i)] =
+        util::Utf16ToUtf8(android::StringPiece16(table.getBasePackageName(i).string()));
+  }
+  return package_map;
 }
 
 static std::unique_ptr<SymbolTable::Symbol> LookupAttributeInTable(
@@ -170,8 +202,7 @@
   }
 
   // We found a resource.
-  std::unique_ptr<SymbolTable::Symbol> s =
-      util::make_unique<SymbolTable::Symbol>();
+  std::unique_ptr<SymbolTable::Symbol> s = util::make_unique<SymbolTable::Symbol>();
   s->id = id;
 
   // Check to see if it is an attribute.
@@ -204,8 +235,7 @@
         return nullptr;
       }
 
-      Maybe<ResourceName> parsed_name =
-          ResourceUtils::ToResourceName(entry_name);
+      Maybe<ResourceName> parsed_name = ResourceUtils::ToResourceName(entry_name);
       if (!parsed_name) {
         return nullptr;
       }
@@ -246,8 +276,7 @@
   }
 
   if (s) {
-    s->is_public =
-        (type_spec_flags & android::ResTable_typeSpec::SPEC_PUBLIC) != 0;
+    s->is_public = (type_spec_flags & android::ResTable_typeSpec::SPEC_PUBLIC) != 0;
     return s;
   }
   return {};
@@ -264,6 +293,11 @@
 
 std::unique_ptr<SymbolTable::Symbol> AssetManagerSymbolSource::FindById(
     ResourceId id) {
+  if (!id.is_valid()) {
+    // Exit early and avoid the error logs from AssetManager.
+    return {};
+  }
+
   const android::ResTable& table = assets_.getResources(false);
   Maybe<ResourceName> maybe_name = GetResourceName(table, id);
   if (!maybe_name) {
@@ -282,8 +316,7 @@
   }
 
   if (s) {
-    s->is_public =
-        (type_spec_flags & android::ResTable_typeSpec::SPEC_PUBLIC) != 0;
+    s->is_public = (type_spec_flags & android::ResTable_typeSpec::SPEC_PUBLIC) != 0;
     return s;
   }
   return {};
diff --git a/tools/aapt2/process/SymbolTable.h b/tools/aapt2/process/SymbolTable.h
index cf597bb..298da4d 100644
--- a/tools/aapt2/process/SymbolTable.h
+++ b/tools/aapt2/process/SymbolTable.h
@@ -47,6 +47,7 @@
 }
 
 class ISymbolSource;
+class NameMangler;
 
 class SymbolTable {
  public:
@@ -72,25 +73,32 @@
     bool is_public = false;
   };
 
-  SymbolTable() : cache_(200), id_cache_(200) {}
+  SymbolTable(NameMangler* mangler) : mangler_(mangler), cache_(200), id_cache_(200) {}
 
+  // Appends a symbol source. The cache is not cleared since entries that
+  // have already been found would take precedence due to ordering.
   void AppendSource(std::unique_ptr<ISymbolSource> source);
+
+  // Prepends a symbol source so that its symbols take precedence. This will
+  // cause the existing cache to be cleared.
   void PrependSource(std::unique_ptr<ISymbolSource> source);
 
-  /**
-   * Never hold on to the result between calls to FindByName or FindById. The
-   * results stored in a cache which may evict entries.
-   */
+  // NOTE: Never hold on to the result between calls to FindByXXX. The
+  // results are stored in a cache which may evict entries on subsequent calls.
   const Symbol* FindByName(const ResourceName& name);
+
+  // NOTE: Never hold on to the result between calls to FindByXXX. The
+  // results are stored in a cache which may evict entries on subsequent calls.
   const Symbol* FindById(const ResourceId& id);
 
-  /**
-   * Let's the ISymbolSource decide whether looking up by name or ID is faster,
-   * if both are available.
-   */
+  // Let's the ISymbolSource decide whether looking up by name or ID is faster,
+  // if both are available.
+  // NOTE: Never hold on to the result between calls to FindByXXX. The
+  // results are stored in a cache which may evict entries on subsequent calls.
   const Symbol* FindByReference(const Reference& ref);
 
  private:
+  NameMangler* mangler_;
   std::vector<std::unique_ptr<ISymbolSource>> sources_;
 
   // We use shared_ptr because unique_ptr is not supported and
@@ -155,6 +163,7 @@
   AssetManagerSymbolSource() = default;
 
   bool AddAssetPath(const android::StringPiece& path);
+  std::map<size_t, std::string> GetAssignedPackageIds() const;
 
   std::unique_ptr<SymbolTable::Symbol> FindByName(
       const ResourceName& name) override;
diff --git a/tools/aapt2/process/SymbolTable_test.cpp b/tools/aapt2/process/SymbolTable_test.cpp
index 9ea0786..bba316f 100644
--- a/tools/aapt2/process/SymbolTable_test.cpp
+++ b/tools/aapt2/process/SymbolTable_test.cpp
@@ -55,4 +55,19 @@
   EXPECT_NE(nullptr, s->attribute);
 }
 
+TEST(SymbolTableTest, FindByName) {
+  std::unique_ptr<ResourceTable> table =
+      test::ResourceTableBuilder()
+          .AddSimple("com.android.app:id/foo")
+          .AddSimple("com.android.app:id/" + NameMangler::MangleEntry("com.android.lib", "foo"))
+          .Build();
+
+  NameMangler mangler(NameManglerPolicy{"com.android.app", {"com.android.lib"}});
+  SymbolTable symbol_table(&mangler);
+  symbol_table.AppendSource(util::make_unique<ResourceTableSymbolSource>(table.get()));
+
+  EXPECT_NE(nullptr, symbol_table.FindByName(test::ParseNameOrDie("id/foo")));
+  EXPECT_NE(nullptr, symbol_table.FindByName(test::ParseNameOrDie("com.android.lib:id/foo")));
+}
+
 }  // namespace aapt
diff --git a/tools/aapt2/readme.md b/tools/aapt2/readme.md
index 8bc4e8c..fedd65c 100644
--- a/tools/aapt2/readme.md
+++ b/tools/aapt2/readme.md
@@ -1,7 +1,27 @@
 # Android Asset Packaging Tool 2.0 (AAPT2) release notes
 
+## Version 2.9
+### `aapt2 link ...`
+- Added sparse resource type encoding, which encodes resource entries that are sparse with
+  a binary search tree representation. Only available when minSdkVersion >= API O or resource
+  qualifier of resource types is >= v26 (or whatever API level O becomes). Enabled with
+  `--enable-sparse-encoding` flag.
+### `aapt2 optimize ...`
+- Adds an optimization pass that supports:
+    - stripping out any density assets that do not match the `--target-densities` list of
+      densities.
+    - resource deduping when the resources are dominated and identical (already happens during
+      `link` phase but this covers apps built with `aapt`).
+    - new sparse resource type encoding with the `--enable-sparse-encoding` flag if possible
+      (minSdkVersion >= O or resource qualifier >= v26).
+
+## Version 2.8
+### `aapt2 link ...`
+- Adds shared library support. Build a shared library with the `--shared-lib` flag.
+  Build a client of a shared library by simply including it via `-I`.
+
 ## Version 2.7
-### `aapt2 compile`
+### `aapt2 compile ...`
 - Fixes bug where psuedolocalization auto-translated strings marked 'translateable="false"'.
 
 ## Version 2.6
diff --git a/tools/aapt2/strip/Strip.cpp b/tools/aapt2/strip/Strip.cpp
deleted file mode 100644
index 7260649..0000000
--- a/tools/aapt2/strip/Strip.cpp
+++ /dev/null
@@ -1,172 +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.
- */
-
-#include <memory>
-#include <vector>
-
-#include "androidfw/StringPiece.h"
-
-#include "Diagnostics.h"
-#include "Flags.h"
-#include "LoadedApk.h"
-#include "split/TableSplitter.h"
-
-using android::StringPiece;
-
-namespace aapt {
-
-struct StripOptions {
-  /** Path to the output APK. */
-  std::string output_path;
-
-  /** List of screen density configurations the APK will be optimized for. */
-  std::vector<ConfigDescription> target_configs;
-};
-
-class StripContext : public IAaptContext {
- public:
-  IDiagnostics* GetDiagnostics() override { return &diagnostics_; }
-
-  NameMangler* GetNameMangler() override {
-    abort();
-    return nullptr;
-  }
-
-  const std::string& GetCompilationPackage() override {
-    static std::string empty;
-    return empty;
-  }
-
-  uint8_t GetPackageId() override { return 0; }
-
-  SymbolTable* GetExternalSymbols() override {
-    abort();
-    return nullptr;
-  }
-
-  bool IsVerbose() override { return verbose_; }
-
-  void SetVerbose(bool val) { verbose_ = val; }
-
-  int GetMinSdkVersion() override { return 0; }
-
- private:
-  StdErrDiagnostics diagnostics_;
-  bool verbose_ = false;
-};
-
-class StripCommand {
- public:
-  StripCommand(StripContext* context, const StripOptions& options)
-      : options_(options),
-        context_(context) {}
-
-  int Run(std::unique_ptr<LoadedApk> apk) {
-    if (context_->IsVerbose()) {
-      context_->GetDiagnostics()->Note(DiagMessage() << "Stripping APK...");
-    }
-
-    // Stripping the APK using the TableSplitter with no splits and the target
-    // densities as the preferred densities. The resource table is modified in
-    // place in the LoadedApk.
-    TableSplitterOptions splitter_options;
-    for (auto& config : options_.target_configs) {
-      splitter_options.preferred_densities.push_back(config.density);
-    }
-    std::vector<SplitConstraints> splits;
-    TableSplitter splitter(splits, splitter_options);
-    splitter.SplitTable(apk->GetResourceTable());
-
-    std::unique_ptr<IArchiveWriter> writer =
-        CreateZipFileArchiveWriter(context_->GetDiagnostics(), options_.output_path);
-    if (!apk->WriteToArchive(context_, writer.get())) {
-      return 1;
-    }
-
-    return 0;
-  }
-
- private:
-  StripOptions options_;
-  StripContext* context_;
-};
-
-int Strip(const std::vector<StringPiece>& args) {
-  StripContext context;
-  StripOptions options;
-  std::string target_densities;
-  bool verbose = false;
-  Flags flags =
-      Flags()
-          .RequiredFlag("-o", "Path to the output APK.", &options.output_path)
-          .RequiredFlag(
-              "--target-densities",
-              "Comma separated list of the screen densities that the APK will "
-              "be optimized for. All the resources that would be unused on "
-              "devices of the given densities will be removed from the APK.",
-              &target_densities)
-          .OptionalSwitch("-v", "Enables verbose logging", &verbose);
-
-  if (!flags.Parse("aapt2 strip", args, &std::cerr)) {
-    return 1;
-  }
-
-  if (flags.GetArgs().size() != 1u) {
-    std::cerr << "must have one APK as argument.\n\n";
-    flags.Usage("aapt2 strip", &std::cerr);
-    return 1;
-  }
-
-  std::unique_ptr<LoadedApk> apk =
-      LoadedApk::LoadApkFromPath(&context, flags.GetArgs()[0]);
-  if (!apk) {
-    return 1;
-  }
-
-  if (verbose) {
-    context.SetVerbose(verbose);
-  }
-
-  // Parse the target screen densities.
-  for (const StringPiece& config_str : util::Tokenize(target_densities, ',')) {
-    ConfigDescription config;
-    if (!ConfigDescription::Parse(config_str, &config) || config.density == 0) {
-      context.GetDiagnostics()->Error(
-          DiagMessage() << "invalid density '" << config_str
-                        << "' for --target-densities option");
-      return 1;
-    }
-
-    // Clear the version that can be automatically added.
-    config.sdkVersion = 0;
-
-    if (config.diff(ConfigDescription::DefaultConfig()) !=
-        ConfigDescription::CONFIG_DENSITY) {
-      context.GetDiagnostics()->Error(
-          DiagMessage() << "invalid density '" << config_str
-                        << "' for --target-densities option. Must be only a "
-                        << "density value.");
-      return 1;
-    }
-
-    options.target_configs.push_back(config);
-  }
-
-  StripCommand cmd(&context, options);
-  return cmd.Run(std::move(apk));
-}
-
-}  // namespace aapt
diff --git a/tools/aapt2/test/Context.h b/tools/aapt2/test/Context.h
index 63e5f16..557cd1b 100644
--- a/tools/aapt2/test/Context.h
+++ b/tools/aapt2/test/Context.h
@@ -33,7 +33,7 @@
 
 class Context : public IAaptContext {
  public:
-  Context() = default;
+  Context() : name_mangler_({}), symbols_(&name_mangler_), min_sdk_version_(0) {}
 
   SymbolTable* GetExternalSymbols() override { return &symbols_; }
 
@@ -63,9 +63,9 @@
   Maybe<std::string> compilation_package_;
   Maybe<uint8_t> package_id_;
   StdErrDiagnostics diagnostics_;
+  NameMangler name_mangler_;
   SymbolTable symbols_;
-  NameMangler name_mangler_ = NameMangler({});
-  int min_sdk_version_ = 0;
+  int min_sdk_version_;
 };
 
 class ContextBuilder {
diff --git a/tools/aapt2/unflatten/BinaryResourceParser.cpp b/tools/aapt2/unflatten/BinaryResourceParser.cpp
index 7098fe9..9158bdd 100644
--- a/tools/aapt2/unflatten/BinaryResourceParser.cpp
+++ b/tools/aapt2/unflatten/BinaryResourceParser.cpp
@@ -248,6 +248,12 @@
         }
         break;
 
+      case android::RES_TABLE_LIBRARY_TYPE:
+        if (!ParseLibrary(parser.chunk())) {
+          return false;
+        }
+        break;
+
       default:
         context_->GetDiagnostics()->Warn(
             DiagMessage(source_)
@@ -395,6 +401,21 @@
   return true;
 }
 
+bool BinaryResourceParser::ParseLibrary(const ResChunk_header* chunk) {
+  DynamicRefTable dynamic_ref_table;
+  if (dynamic_ref_table.load(reinterpret_cast<const ResTable_lib_header*>(chunk)) != NO_ERROR) {
+    return false;
+  }
+
+  const KeyedVector<String16, uint8_t>& entries = dynamic_ref_table.entries();
+  const size_t count = entries.size();
+  for (size_t i = 0; i < count; i++) {
+    table_->included_packages_[entries.valueAt(i)] =
+        util::Utf16ToUtf8(StringPiece16(entries.keyAt(i).string()));
+  }
+  return true;
+}
+
 std::unique_ptr<Item> BinaryResourceParser::ParseValue(
     const ResourceNameRef& name, const ConfigDescription& config,
     const Res_value* value, uint16_t flags) {
@@ -437,10 +458,14 @@
   }
 
   if (value->dataType == Res_value::TYPE_REFERENCE ||
-      value->dataType == Res_value::TYPE_ATTRIBUTE) {
-    const Reference::Type type = (value->dataType == Res_value::TYPE_REFERENCE)
-                                     ? Reference::Type::kResource
-                                     : Reference::Type::kAttribute;
+      value->dataType == Res_value::TYPE_ATTRIBUTE ||
+      value->dataType == Res_value::TYPE_DYNAMIC_REFERENCE ||
+      value->dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE) {
+    Reference::Type type = Reference::Type::kResource;
+    if (value->dataType == Res_value::TYPE_ATTRIBUTE ||
+        value->dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE) {
+      type = Reference::Type::kAttribute;
+    }
 
     if (data == 0) {
       // A reference of 0, must be the magic @null reference.
diff --git a/tools/aapt2/unflatten/BinaryResourceParser.h b/tools/aapt2/unflatten/BinaryResourceParser.h
index dc668fd..e3dd802 100644
--- a/tools/aapt2/unflatten/BinaryResourceParser.h
+++ b/tools/aapt2/unflatten/BinaryResourceParser.h
@@ -61,6 +61,7 @@
   bool ParseTypeSpec(const android::ResChunk_header* chunk);
   bool ParseType(const ResourceTablePackage* package,
                  const android::ResChunk_header* chunk);
+  bool ParseLibrary(const android::ResChunk_header* chunk);
 
   std::unique_ptr<Item> ParseValue(const ResourceNameRef& name,
                                    const ConfigDescription& config,
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
index 3d5d5c6..df3ce19 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
@@ -640,6 +640,10 @@
             return AccessibilityManager.getInstance(this);
         }
 
+        if (AUTO_FILL_MANAGER_SERVICE.equals(service)) {
+            return null;
+        }
+
         throw new UnsupportedOperationException("Unsupported Service: " + service);
     }
 
diff --git a/wifi/java/android/net/wifi/WifiConfiguration.java b/wifi/java/android/net/wifi/WifiConfiguration.java
index 3eb9934..a4ab64f 100644
--- a/wifi/java/android/net/wifi/WifiConfiguration.java
+++ b/wifi/java/android/net/wifi/WifiConfiguration.java
@@ -1305,6 +1305,7 @@
             setConnectChoice(source.getConnectChoice());
             setConnectChoiceTimestamp(source.getConnectChoiceTimestamp());
             setHasEverConnected(source.getHasEverConnected());
+            setNotRecommended(source.isNotRecommended());
         }
 
         public void writeToParcel(Parcel dest) {
diff --git a/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java b/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java
index 5f949747..632cfaf 100644
--- a/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java
+++ b/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java
@@ -20,6 +20,7 @@
 import static org.junit.Assert.assertEquals;
 
 import android.os.Parcel;
+import android.net.wifi.WifiConfiguration.NetworkSelectionStatus;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -66,4 +67,35 @@
 
         assertArrayEquals(bytes, rebytes);
     }
+
+    @Test
+    public void testNetworkSelectionStatusCopy() {
+        NetworkSelectionStatus networkSelectionStatus = new NetworkSelectionStatus();
+        networkSelectionStatus.setNotRecommended(true);
+
+        NetworkSelectionStatus copy = new NetworkSelectionStatus();
+        copy.copy(networkSelectionStatus);
+
+        assertEquals(networkSelectionStatus.isNotRecommended(), copy.isNotRecommended());
+    }
+
+    @Test
+    public void testNetworkSelectionStatusParcel() {
+        NetworkSelectionStatus networkSelectionStatus = new NetworkSelectionStatus();
+        networkSelectionStatus.setNotRecommended(true);
+
+        Parcel parcelW = Parcel.obtain();
+        networkSelectionStatus.writeToParcel(parcelW);
+        byte[] bytes = parcelW.marshall();
+        parcelW.recycle();
+
+        Parcel parcelR = Parcel.obtain();
+        parcelR.unmarshall(bytes, 0, bytes.length);
+        parcelR.setDataPosition(0);
+
+        NetworkSelectionStatus copy = new NetworkSelectionStatus();
+        copy.readFromParcel(parcelR);
+
+        assertEquals(networkSelectionStatus.isNotRecommended(), copy.isNotRecommended());
+    }
 }