Merge "Fix broken javadoc links"
diff --git a/api/current.txt b/api/current.txt
index a2b6d51..e789d5b 100755
--- a/api/current.txt
+++ b/api/current.txt
@@ -27855,7 +27855,7 @@
     method public android.os.ParcelFileDescriptor establish();
     method public android.net.VpnService.Builder setBlocking(boolean);
     method public android.net.VpnService.Builder setConfigureIntent(android.app.PendingIntent);
-    method public android.net.VpnService.Builder setHttpProxy(android.net.ProxyInfo);
+    method public android.net.VpnService.Builder setHttpProxy(@NonNull android.net.ProxyInfo);
     method public android.net.VpnService.Builder setMetered(boolean);
     method public android.net.VpnService.Builder setMtu(int);
     method public android.net.VpnService.Builder setSession(String);
@@ -40417,6 +40417,7 @@
     method public static void chown(String, int, int) throws android.system.ErrnoException;
     method public static void close(java.io.FileDescriptor) throws android.system.ErrnoException;
     method public static void connect(java.io.FileDescriptor, java.net.InetAddress, int) throws android.system.ErrnoException, java.net.SocketException;
+    method public static void connect(java.io.FileDescriptor, java.net.SocketAddress) throws android.system.ErrnoException, java.net.SocketException;
     method public static java.io.FileDescriptor dup(java.io.FileDescriptor) throws android.system.ErrnoException;
     method public static java.io.FileDescriptor dup2(java.io.FileDescriptor, int) throws android.system.ErrnoException;
     method public static String[] environ();
@@ -41246,11 +41247,11 @@
 
   public final class CallIdentification implements android.os.Parcelable {
     method public int describeContents();
-    method @NonNull public String getCallScreeningAppName();
+    method @NonNull public CharSequence getCallScreeningAppName();
     method @NonNull public String getCallScreeningPackageName();
-    method @Nullable public String getDescription();
-    method @Nullable public String getDetails();
-    method @Nullable public String getName();
+    method @Nullable public CharSequence getDescription();
+    method @Nullable public CharSequence getDetails();
+    method @Nullable public CharSequence getName();
     method public int getNuisanceConfidence();
     method @Nullable public android.graphics.drawable.Icon getPhoto();
     method public void writeToParcel(android.os.Parcel, int);
@@ -41265,9 +41266,9 @@
   public static class CallIdentification.Builder {
     ctor public CallIdentification.Builder();
     method public android.telecom.CallIdentification build();
-    method public android.telecom.CallIdentification.Builder setDescription(@Nullable String);
-    method public android.telecom.CallIdentification.Builder setDetails(@Nullable String);
-    method public android.telecom.CallIdentification.Builder setName(@Nullable String);
+    method public android.telecom.CallIdentification.Builder setDescription(@Nullable CharSequence);
+    method public android.telecom.CallIdentification.Builder setDetails(@Nullable CharSequence);
+    method public android.telecom.CallIdentification.Builder setName(@Nullable CharSequence);
     method public android.telecom.CallIdentification.Builder setNuisanceConfidence(int);
     method public android.telecom.CallIdentification.Builder setPhoto(@Nullable android.graphics.drawable.Icon);
   }
@@ -42762,6 +42763,7 @@
     method @Deprecated public int getCdmaDbm();
     method @Deprecated public int getCdmaEcio();
     method @NonNull public java.util.List<android.telephony.CellSignalStrength> getCellSignalStrengths();
+    method public <T extends android.telephony.CellSignalStrength> java.util.List<T> getCellSignalStrengths(@NonNull Class<T>);
     method @Deprecated public int getEvdoDbm();
     method @Deprecated public int getEvdoEcio();
     method @Deprecated public int getEvdoSnr();
@@ -43070,7 +43072,7 @@
     method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public String getSubscriberId();
     method public String getTypeAllocationCode();
     method public String getTypeAllocationCode(int);
-    method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public java.util.List<android.telephony.UiccCardInfo> getUiccCardsInfo();
+    method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") @NonNull public java.util.List<android.telephony.UiccCardInfo> getUiccCardsInfo();
     method @Nullable @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public String getVisualVoicemailPackageName();
     method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public String getVoiceMailAlphaTag();
     method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public String getVoiceMailNumber();
@@ -43237,13 +43239,13 @@
   }
 
   public final class UiccCardInfo implements android.os.Parcelable {
-    ctor public UiccCardInfo(boolean, int, String, String, int);
     method public int describeContents();
     method public int getCardId();
-    method public String getEid();
-    method public String getIccId();
+    method @Nullable public String getEid();
+    method @Nullable public String getIccId();
     method public int getSlotIndex();
     method public boolean isEuicc();
+    method public boolean isRemovable();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.telephony.UiccCardInfo> CREATOR;
   }
@@ -43558,465 +43560,6 @@
 
 }
 
-package android.telephony.ims {
-
-  public class Rcs1To1Thread extends android.telephony.ims.RcsThread {
-    method @WorkerThread public long getFallbackThreadId() throws android.telephony.ims.RcsMessageStoreException;
-    method @NonNull @WorkerThread public android.telephony.ims.RcsParticipant getRecipient() throws android.telephony.ims.RcsMessageStoreException;
-    method public boolean isGroup();
-    method @WorkerThread public void setFallbackThreadId(long) throws android.telephony.ims.RcsMessageStoreException;
-  }
-
-  public abstract class RcsEvent {
-    ctor protected RcsEvent(long);
-    method public long getTimestamp();
-  }
-
-  public final class RcsEventQueryParams implements android.os.Parcelable {
-    method public int describeContents();
-    method @android.telephony.ims.RcsEventQueryParams.EventType public int getEventType();
-    method public int getLimit();
-    method public boolean getSortDirection();
-    method public int getSortingProperty();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final int ALL_EVENTS = -1; // 0xffffffff
-    field public static final int ALL_GROUP_THREAD_EVENTS = 0; // 0x0
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsEventQueryParams> CREATOR;
-    field public static final int GROUP_THREAD_ICON_CHANGED_EVENT = 8; // 0x8
-    field public static final int GROUP_THREAD_NAME_CHANGED_EVENT = 16; // 0x10
-    field public static final int GROUP_THREAD_PARTICIPANT_JOINED_EVENT = 2; // 0x2
-    field public static final int GROUP_THREAD_PARTICIPANT_LEFT_EVENT = 4; // 0x4
-    field public static final int PARTICIPANT_ALIAS_CHANGED_EVENT = 1; // 0x1
-    field public static final int SORT_BY_CREATION_ORDER = 0; // 0x0
-    field public static final int SORT_BY_TIMESTAMP = 1; // 0x1
-  }
-
-  public static class RcsEventQueryParams.Builder {
-    ctor public RcsEventQueryParams.Builder();
-    method public android.telephony.ims.RcsEventQueryParams build();
-    method @CheckResult public android.telephony.ims.RcsEventQueryParams.Builder setEventType(@android.telephony.ims.RcsEventQueryParams.EventType int);
-    method @CheckResult public android.telephony.ims.RcsEventQueryParams.Builder setGroupThread(@NonNull android.telephony.ims.RcsGroupThread);
-    method @CheckResult public android.telephony.ims.RcsEventQueryParams.Builder setResultLimit(@IntRange(from=0) int) throws java.security.InvalidParameterException;
-    method @CheckResult public android.telephony.ims.RcsEventQueryParams.Builder setSortDirection(boolean);
-    method @CheckResult public android.telephony.ims.RcsEventQueryParams.Builder setSortProperty(@android.telephony.ims.RcsEventQueryParams.SortingProperty int);
-  }
-
-  @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsEventQueryParams.ALL_EVENTS, android.telephony.ims.RcsEventQueryParams.ALL_GROUP_THREAD_EVENTS, android.telephony.ims.RcsEventQueryParams.PARTICIPANT_ALIAS_CHANGED_EVENT, android.telephony.ims.RcsEventQueryParams.GROUP_THREAD_PARTICIPANT_JOINED_EVENT, android.telephony.ims.RcsEventQueryParams.GROUP_THREAD_PARTICIPANT_LEFT_EVENT, android.telephony.ims.RcsEventQueryParams.GROUP_THREAD_NAME_CHANGED_EVENT, android.telephony.ims.RcsEventQueryParams.GROUP_THREAD_ICON_CHANGED_EVENT}) public static @interface RcsEventQueryParams.EventType {
-  }
-
-  @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsEventQueryParams.SORT_BY_CREATION_ORDER, android.telephony.ims.RcsEventQueryParams.SORT_BY_TIMESTAMP}) public static @interface RcsEventQueryParams.SortingProperty {
-  }
-
-  public class RcsEventQueryResult {
-    method public android.telephony.ims.RcsQueryContinuationToken getContinuationToken();
-    method public java.util.List<android.telephony.ims.RcsEvent> getEvents();
-  }
-
-  public final class RcsFileTransferCreationParams implements android.os.Parcelable {
-    method public int describeContents();
-    method public String getContentMimeType();
-    method public android.net.Uri getContentUri();
-    method public long getFileSize();
-    method @android.telephony.ims.RcsFileTransferPart.RcsFileTransferStatus public int getFileTransferStatus();
-    method public int getHeight();
-    method public long getMediaDuration();
-    method public String getPreviewMimeType();
-    method public android.net.Uri getPreviewUri();
-    method public String getRcsFileTransferSessionId();
-    method public long getTransferOffset();
-    method public int getWidth();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsFileTransferCreationParams> CREATOR;
-  }
-
-  public class RcsFileTransferCreationParams.Builder {
-    ctor public RcsFileTransferCreationParams.Builder();
-    method public android.telephony.ims.RcsFileTransferCreationParams build();
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setContentMimeType(String);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setContentUri(android.net.Uri);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setFileSize(long);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setFileTransferSessionId(String);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setFileTransferStatus(@android.telephony.ims.RcsFileTransferPart.RcsFileTransferStatus int);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setHeight(int);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setMediaDuration(long);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setPreviewMimeType(String);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setPreviewUri(android.net.Uri);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setTransferOffset(long);
-    method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setWidth(int);
-  }
-
-  public class RcsFileTransferPart {
-    method @WorkerThread @Nullable public String getContentMimeType() throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable @WorkerThread public android.net.Uri getContentUri() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public long getFileSize() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public String getFileTransferSessionId() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @android.telephony.ims.RcsFileTransferPart.RcsFileTransferStatus public int getFileTransferStatus() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public int getHeight() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public long getLength() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public String getPreviewMimeType() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public android.net.Uri getPreviewUri() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public long getTransferOffset() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public int getWidth() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setContentMimeType(String) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setContentUri(android.net.Uri) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setFileSize(long) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setFileTransferSessionId(String) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setFileTransferStatus(@android.telephony.ims.RcsFileTransferPart.RcsFileTransferStatus int) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setHeight(int) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setLength(long) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setPreviewMimeType(String) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setPreviewUri(android.net.Uri) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setTransferOffset(long) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setWidth(int) throws android.telephony.ims.RcsMessageStoreException;
-    field public static final int DOWNLOADING = 6; // 0x6
-    field public static final int DOWNLOADING_CANCELLED = 9; // 0x9
-    field public static final int DOWNLOADING_FAILED = 8; // 0x8
-    field public static final int DOWNLOADING_PAUSED = 7; // 0x7
-    field public static final int DRAFT = 1; // 0x1
-    field public static final int NOT_SET = 0; // 0x0
-    field public static final int SENDING = 2; // 0x2
-    field public static final int SENDING_CANCELLED = 5; // 0x5
-    field public static final int SENDING_FAILED = 4; // 0x4
-    field public static final int SENDING_PAUSED = 3; // 0x3
-    field public static final int SUCCEEDED = 10; // 0xa
-  }
-
-  @IntDef({android.telephony.ims.RcsFileTransferPart.DRAFT, android.telephony.ims.RcsFileTransferPart.SENDING, android.telephony.ims.RcsFileTransferPart.SENDING_PAUSED, android.telephony.ims.RcsFileTransferPart.SENDING_FAILED, android.telephony.ims.RcsFileTransferPart.SENDING_CANCELLED, android.telephony.ims.RcsFileTransferPart.DOWNLOADING, android.telephony.ims.RcsFileTransferPart.DOWNLOADING_PAUSED, android.telephony.ims.RcsFileTransferPart.DOWNLOADING_FAILED, android.telephony.ims.RcsFileTransferPart.DOWNLOADING_CANCELLED, android.telephony.ims.RcsFileTransferPart.SUCCEEDED}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface RcsFileTransferPart.RcsFileTransferStatus {
-  }
-
-  public class RcsGroupThread extends android.telephony.ims.RcsThread {
-    method @WorkerThread public void addParticipant(@NonNull android.telephony.ims.RcsParticipant) throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable @WorkerThread public android.net.Uri getConferenceUri() throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable public android.net.Uri getGroupIcon() throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable @WorkerThread public String getGroupName() throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable @WorkerThread public android.telephony.ims.RcsParticipant getOwner() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public java.util.Set<android.telephony.ims.RcsParticipant> getParticipants() throws android.telephony.ims.RcsMessageStoreException;
-    method public boolean isGroup();
-    method @WorkerThread public void removeParticipant(@NonNull android.telephony.ims.RcsParticipant) throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable @WorkerThread public void setConferenceUri(android.net.Uri) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setGroupIcon(@Nullable android.net.Uri) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setGroupName(String) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setOwner(@Nullable android.telephony.ims.RcsParticipant) throws android.telephony.ims.RcsMessageStoreException;
-  }
-
-  public abstract class RcsGroupThreadEvent extends android.telephony.ims.RcsEvent {
-    method @NonNull public android.telephony.ims.RcsParticipant getOriginatingParticipant();
-    method @NonNull public android.telephony.ims.RcsGroupThread getRcsGroupThread();
-  }
-
-  public final class RcsGroupThreadIconChangedEvent extends android.telephony.ims.RcsGroupThreadEvent {
-    ctor public RcsGroupThreadIconChangedEvent(long, @NonNull android.telephony.ims.RcsGroupThread, @NonNull android.telephony.ims.RcsParticipant, @Nullable android.net.Uri);
-    method @Nullable public android.net.Uri getNewIcon();
-  }
-
-  public final class RcsGroupThreadNameChangedEvent extends android.telephony.ims.RcsGroupThreadEvent {
-    ctor public RcsGroupThreadNameChangedEvent(long, @NonNull android.telephony.ims.RcsGroupThread, @NonNull android.telephony.ims.RcsParticipant, @Nullable String);
-    method @Nullable public String getNewName();
-  }
-
-  public final class RcsGroupThreadParticipantJoinedEvent extends android.telephony.ims.RcsGroupThreadEvent {
-    ctor public RcsGroupThreadParticipantJoinedEvent(long, @NonNull android.telephony.ims.RcsGroupThread, @NonNull android.telephony.ims.RcsParticipant, @NonNull android.telephony.ims.RcsParticipant);
-    method public android.telephony.ims.RcsParticipant getJoinedParticipant();
-  }
-
-  public final class RcsGroupThreadParticipantLeftEvent extends android.telephony.ims.RcsGroupThreadEvent {
-    ctor public RcsGroupThreadParticipantLeftEvent(long, @NonNull android.telephony.ims.RcsGroupThread, @NonNull android.telephony.ims.RcsParticipant, @NonNull android.telephony.ims.RcsParticipant);
-    method @NonNull public android.telephony.ims.RcsParticipant getLeavingParticipant();
-    method public void persist() throws android.telephony.ims.RcsMessageStoreException;
-  }
-
-  public class RcsIncomingMessage extends android.telephony.ims.RcsMessage {
-    method @WorkerThread public long getArrivalTimestamp() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public long getSeenTimestamp() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public android.telephony.ims.RcsParticipant getSenderParticipant() throws android.telephony.ims.RcsMessageStoreException;
-    method public boolean isIncoming();
-    method @WorkerThread public void setArrivalTimestamp(long) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setSeenTimestamp(long) throws android.telephony.ims.RcsMessageStoreException;
-  }
-
-  public final class RcsIncomingMessageCreationParams extends android.telephony.ims.RcsMessageCreationParams implements android.os.Parcelable {
-    method public int describeContents();
-    method public long getArrivalTimestamp();
-    method public long getSeenTimestamp();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsIncomingMessageCreationParams> CREATOR;
-  }
-
-  public static class RcsIncomingMessageCreationParams.Builder extends android.telephony.ims.RcsMessageCreationParams.Builder {
-    ctor public RcsIncomingMessageCreationParams.Builder(long, long, int);
-    method public android.telephony.ims.RcsIncomingMessageCreationParams build();
-    method @CheckResult public android.telephony.ims.RcsIncomingMessageCreationParams.Builder setArrivalTimestamp(long);
-    method @CheckResult public android.telephony.ims.RcsIncomingMessageCreationParams.Builder setSeenTimestamp(long);
-    method @CheckResult public android.telephony.ims.RcsIncomingMessageCreationParams.Builder setSenderParticipant(android.telephony.ims.RcsParticipant);
-  }
-
-  public class RcsManager {
-    method public android.telephony.ims.RcsMessageStore getRcsMessageStore();
-  }
-
-  public abstract class RcsMessage {
-    method @NonNull @WorkerThread public java.util.Set<android.telephony.ims.RcsFileTransferPart> getFileTransferParts() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public double getLatitude() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public double getLongitude() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public long getOriginationTimestamp() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public String getRcsMessageId() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @android.telephony.ims.RcsMessage.RcsMessageStatus public int getStatus() throws android.telephony.ims.RcsMessageStoreException;
-    method public int getSubscriptionId() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public String getText() throws android.telephony.ims.RcsMessageStoreException;
-    method @NonNull @WorkerThread public android.telephony.ims.RcsFileTransferPart insertFileTransfer(android.telephony.ims.RcsFileTransferCreationParams) throws android.telephony.ims.RcsMessageStoreException;
-    method public abstract boolean isIncoming();
-    method @WorkerThread public void removeFileTransferPart(@NonNull android.telephony.ims.RcsFileTransferPart) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setLatitude(double) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setLongitude(double) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setOriginationTimestamp(long) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setRcsMessageId(String) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setStatus(@android.telephony.ims.RcsMessage.RcsMessageStatus int) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setSubscriptionId(int) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setText(String) throws android.telephony.ims.RcsMessageStoreException;
-    field public static final int DRAFT = 1; // 0x1
-    field public static final int FAILED = 6; // 0x6
-    field public static final double LOCATION_NOT_SET = 4.9E-324;
-    field public static final int NOT_SET = 0; // 0x0
-    field public static final int QUEUED = 2; // 0x2
-    field public static final int RECEIVED = 7; // 0x7
-    field public static final int RETRYING = 5; // 0x5
-    field public static final int SEEN = 9; // 0x9
-    field public static final int SENDING = 3; // 0x3
-    field public static final int SENT = 4; // 0x4
-  }
-
-  @IntDef({android.telephony.ims.RcsMessage.DRAFT, android.telephony.ims.RcsMessage.QUEUED, android.telephony.ims.RcsMessage.SENDING, android.telephony.ims.RcsMessage.SENT, android.telephony.ims.RcsMessage.RETRYING, android.telephony.ims.RcsMessage.FAILED, android.telephony.ims.RcsMessage.RECEIVED, android.telephony.ims.RcsMessage.SEEN}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface RcsMessage.RcsMessageStatus {
-  }
-
-  public class RcsMessageCreationParams {
-    ctor protected RcsMessageCreationParams(android.telephony.ims.RcsMessageCreationParams.Builder);
-    method public double getLatitude();
-    method public double getLongitude();
-    method public int getMessageStatus();
-    method public long getOriginationTimestamp();
-    method @Nullable public String getRcsMessageGlobalId();
-    method public int getSubId();
-    method @Nullable public String getText();
-  }
-
-  public static class RcsMessageCreationParams.Builder {
-    method public android.telephony.ims.RcsMessageCreationParams build();
-    method @CheckResult public android.telephony.ims.RcsMessageCreationParams.Builder setLatitude(double);
-    method @CheckResult public android.telephony.ims.RcsMessageCreationParams.Builder setLongitude(double);
-    method @CheckResult public android.telephony.ims.RcsMessageCreationParams.Builder setRcsMessageId(String);
-    method @CheckResult public android.telephony.ims.RcsMessageCreationParams.Builder setStatus(@android.telephony.ims.RcsMessage.RcsMessageStatus int);
-    method @CheckResult public android.telephony.ims.RcsMessageCreationParams.Builder setText(String);
-  }
-
-  public final class RcsMessageQueryParams implements android.os.Parcelable {
-    method public int describeContents();
-    method public int getFileTransferPresence();
-    method public int getLimit();
-    method public String getMessageLike();
-    method public int getMessageType();
-    method public boolean getSortDirection();
-    method @android.telephony.ims.RcsMessageQueryParams.SortingProperty public int getSortingProperty();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsMessageQueryParams> CREATOR;
-    field public static final int MESSAGES_WITHOUT_FILE_TRANSFERS = 8; // 0x8
-    field public static final int MESSAGES_WITH_FILE_TRANSFERS = 4; // 0x4
-    field public static final int MESSAGE_TYPE_INCOMING = 1; // 0x1
-    field public static final int MESSAGE_TYPE_OUTGOING = 2; // 0x2
-    field public static final int SORT_BY_CREATION_ORDER = 0; // 0x0
-    field public static final int SORT_BY_TIMESTAMP = 1; // 0x1
-  }
-
-  public static class RcsMessageQueryParams.Builder {
-    ctor public RcsMessageQueryParams.Builder();
-    method public android.telephony.ims.RcsMessageQueryParams build();
-    method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setFileTransferPresence(int);
-    method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setMessageLike(String);
-    method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setMessageType(int);
-    method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setResultLimit(@IntRange(from=0) int) throws java.security.InvalidParameterException;
-    method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setSortDirection(boolean);
-    method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setSortProperty(@android.telephony.ims.RcsMessageQueryParams.SortingProperty int);
-    method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setThread(@Nullable android.telephony.ims.RcsThread);
-  }
-
-  @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsMessageQueryParams.SORT_BY_CREATION_ORDER, android.telephony.ims.RcsMessageQueryParams.SORT_BY_TIMESTAMP}) public static @interface RcsMessageQueryParams.SortingProperty {
-  }
-
-  public final class RcsMessageQueryResult implements android.os.Parcelable {
-    method public int describeContents();
-    method @Nullable public android.telephony.ims.RcsQueryContinuationToken getContinuationToken();
-    method @NonNull public java.util.List<android.telephony.ims.RcsMessage> getMessages();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsMessageQueryResult> CREATOR;
-  }
-
-  public final class RcsMessageSnippet implements android.os.Parcelable {
-    method public int describeContents();
-    method @android.telephony.ims.RcsMessage.RcsMessageStatus public int getSnippetStatus();
-    method @Nullable public String getSnippetText();
-    method public long getSnippetTimestamp();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsMessageSnippet> CREATOR;
-  }
-
-  public class RcsMessageStore {
-    ctor public RcsMessageStore();
-    method @WorkerThread @NonNull public android.telephony.ims.RcsGroupThread createGroupThread(@Nullable java.util.List<android.telephony.ims.RcsParticipant>, @Nullable String, @Nullable android.net.Uri) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.Rcs1To1Thread createRcs1To1Thread(@NonNull android.telephony.ims.RcsParticipant) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsParticipant createRcsParticipant(String, @Nullable String) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void deleteThread(@NonNull android.telephony.ims.RcsThread) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsEventQueryResult getRcsEvents(@Nullable android.telephony.ims.RcsEventQueryParams) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsEventQueryResult getRcsEvents(@NonNull android.telephony.ims.RcsQueryContinuationToken) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsMessageQueryResult getRcsMessages(@Nullable android.telephony.ims.RcsMessageQueryParams) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsMessageQueryResult getRcsMessages(@NonNull android.telephony.ims.RcsQueryContinuationToken) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsParticipantQueryResult getRcsParticipants(@Nullable android.telephony.ims.RcsParticipantQueryParams) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsParticipantQueryResult getRcsParticipants(@NonNull android.telephony.ims.RcsQueryContinuationToken) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsThreadQueryResult getRcsThreads(@Nullable android.telephony.ims.RcsThreadQueryParams) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsThreadQueryResult getRcsThreads(@NonNull android.telephony.ims.RcsQueryContinuationToken) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public void persistRcsEvent(android.telephony.ims.RcsEvent) throws android.telephony.ims.RcsMessageStoreException;
-  }
-
-  public class RcsMessageStoreException extends java.lang.Exception {
-    ctor public RcsMessageStoreException(String);
-  }
-
-  public class RcsOutgoingMessage extends android.telephony.ims.RcsMessage {
-    method @NonNull @WorkerThread public java.util.List<android.telephony.ims.RcsOutgoingMessageDelivery> getOutgoingDeliveries() throws android.telephony.ims.RcsMessageStoreException;
-    method public boolean isIncoming();
-  }
-
-  public final class RcsOutgoingMessageCreationParams extends android.telephony.ims.RcsMessageCreationParams 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.telephony.ims.RcsOutgoingMessageCreationParams> CREATOR;
-  }
-
-  public static class RcsOutgoingMessageCreationParams.Builder extends android.telephony.ims.RcsMessageCreationParams.Builder {
-    ctor public RcsOutgoingMessageCreationParams.Builder(long, int);
-    method public android.telephony.ims.RcsOutgoingMessageCreationParams build();
-  }
-
-  public class RcsOutgoingMessageDelivery {
-    method @WorkerThread public long getDeliveredTimestamp() throws android.telephony.ims.RcsMessageStoreException;
-    method @NonNull public android.telephony.ims.RcsOutgoingMessage getMessage();
-    method @NonNull public android.telephony.ims.RcsParticipant getRecipient();
-    method @WorkerThread public long getSeenTimestamp() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @android.telephony.ims.RcsMessage.RcsMessageStatus public int getStatus() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setDeliveredTimestamp(long) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setSeenTimestamp(long) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setStatus(@android.telephony.ims.RcsMessage.RcsMessageStatus int) throws android.telephony.ims.RcsMessageStoreException;
-  }
-
-  public class RcsParticipant {
-    method @Nullable @WorkerThread public String getAlias() throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable @WorkerThread public String getCanonicalAddress() throws android.telephony.ims.RcsMessageStoreException;
-    method @Nullable @WorkerThread public String getContactId() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setAlias(String) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void setContactId(String) throws android.telephony.ims.RcsMessageStoreException;
-  }
-
-  public final class RcsParticipantAliasChangedEvent extends android.telephony.ims.RcsEvent {
-    ctor public RcsParticipantAliasChangedEvent(long, @NonNull android.telephony.ims.RcsParticipant, @Nullable String);
-    method @Nullable public String getNewAlias();
-    method @NonNull public android.telephony.ims.RcsParticipant getParticipant();
-  }
-
-  public final class RcsParticipantQueryParams implements android.os.Parcelable {
-    method public int describeContents();
-    method public String getAliasLike();
-    method public String getCanonicalAddressLike();
-    method public int getLimit();
-    method public boolean getSortDirection();
-    method public int getSortingProperty();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsParticipantQueryParams> CREATOR;
-    field public static final int SORT_BY_ALIAS = 1; // 0x1
-    field public static final int SORT_BY_CANONICAL_ADDRESS = 2; // 0x2
-    field public static final int SORT_BY_CREATION_ORDER = 0; // 0x0
-  }
-
-  public static class RcsParticipantQueryParams.Builder {
-    ctor public RcsParticipantQueryParams.Builder();
-    method public android.telephony.ims.RcsParticipantQueryParams build();
-    method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setAliasLike(String);
-    method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setCanonicalAddressLike(String);
-    method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setResultLimit(@IntRange(from=0) int) throws java.security.InvalidParameterException;
-    method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setSortDirection(boolean);
-    method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setSortProperty(@android.telephony.ims.RcsParticipantQueryParams.SortingProperty int);
-    method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setThread(android.telephony.ims.RcsThread);
-  }
-
-  @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsParticipantQueryParams.SORT_BY_CREATION_ORDER, android.telephony.ims.RcsParticipantQueryParams.SORT_BY_ALIAS, android.telephony.ims.RcsParticipantQueryParams.SORT_BY_CANONICAL_ADDRESS}) public static @interface RcsParticipantQueryParams.SortingProperty {
-  }
-
-  public final class RcsParticipantQueryResult implements android.os.Parcelable {
-    method public int describeContents();
-    method @Nullable public android.telephony.ims.RcsQueryContinuationToken getContinuationToken();
-    method @NonNull public java.util.List<android.telephony.ims.RcsParticipant> getParticipants();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsParticipantQueryResult> CREATOR;
-  }
-
-  public final class RcsQueryContinuationToken implements android.os.Parcelable {
-    method public int describeContents();
-    method @android.telephony.ims.RcsQueryContinuationToken.ContinuationTokenType public int getQueryType();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsQueryContinuationToken> CREATOR;
-    field public static final int EVENT_QUERY_CONTINUATION_TOKEN_TYPE = 0; // 0x0
-    field public static final int MESSAGE_QUERY_CONTINUATION_TOKEN_TYPE = 1; // 0x1
-    field public static final int PARTICIPANT_QUERY_CONTINUATION_TOKEN_TYPE = 2; // 0x2
-    field public static final int THREAD_QUERY_CONTINUATION_TOKEN_TYPE = 3; // 0x3
-  }
-
-  @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsQueryContinuationToken.EVENT_QUERY_CONTINUATION_TOKEN_TYPE, android.telephony.ims.RcsQueryContinuationToken.MESSAGE_QUERY_CONTINUATION_TOKEN_TYPE, android.telephony.ims.RcsQueryContinuationToken.PARTICIPANT_QUERY_CONTINUATION_TOKEN_TYPE, android.telephony.ims.RcsQueryContinuationToken.THREAD_QUERY_CONTINUATION_TOKEN_TYPE}) public static @interface RcsQueryContinuationToken.ContinuationTokenType {
-  }
-
-  public abstract class RcsThread {
-    method @WorkerThread @NonNull public android.telephony.ims.RcsIncomingMessage addIncomingMessage(@NonNull android.telephony.ims.RcsIncomingMessageCreationParams) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsOutgoingMessage addOutgoingMessage(@NonNull android.telephony.ims.RcsOutgoingMessageCreationParams) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread public void deleteMessage(@NonNull android.telephony.ims.RcsMessage) throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsMessageQueryResult getMessages() throws android.telephony.ims.RcsMessageStoreException;
-    method @WorkerThread @NonNull public android.telephony.ims.RcsMessageSnippet getSnippet() throws android.telephony.ims.RcsMessageStoreException;
-    method public abstract boolean isGroup();
-  }
-
-  public final class RcsThreadQueryParams implements android.os.Parcelable {
-    method public int describeContents();
-    method public int getLimit();
-    method public boolean getSortDirection();
-    method @android.telephony.ims.RcsThreadQueryParams.SortingProperty public int getSortingProperty();
-    method public int getThreadType();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsThreadQueryParams> CREATOR;
-    field public static final int SORT_BY_CREATION_ORDER = 0; // 0x0
-    field public static final int SORT_BY_TIMESTAMP = 1; // 0x1
-    field public static final int THREAD_TYPE_1_TO_1 = 2; // 0x2
-    field public static final int THREAD_TYPE_GROUP = 1; // 0x1
-  }
-
-  public static class RcsThreadQueryParams.Builder {
-    ctor public RcsThreadQueryParams.Builder();
-    method public android.telephony.ims.RcsThreadQueryParams build();
-    method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setParticipant(@NonNull android.telephony.ims.RcsParticipant);
-    method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setParticipants(@NonNull java.util.List<android.telephony.ims.RcsParticipant>);
-    method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setResultLimit(@IntRange(from=0) int) throws java.security.InvalidParameterException;
-    method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setSortDirection(boolean);
-    method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setSortProperty(@android.telephony.ims.RcsThreadQueryParams.SortingProperty int);
-    method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setThreadType(int);
-  }
-
-  @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsThreadQueryParams.SORT_BY_CREATION_ORDER, android.telephony.ims.RcsThreadQueryParams.SORT_BY_TIMESTAMP}) public static @interface RcsThreadQueryParams.SortingProperty {
-  }
-
-  public final class RcsThreadQueryResult implements android.os.Parcelable {
-    method public int describeContents();
-    method @Nullable public android.telephony.ims.RcsQueryContinuationToken getContinuationToken();
-    method @NonNull public java.util.List<android.telephony.ims.RcsThread> getThreads();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsThreadQueryResult> CREATOR;
-  }
-
-}
-
 package android.telephony.mbms {
 
   public class DownloadProgressListener {
diff --git a/api/system-current.txt b/api/system-current.txt
index d8859b8..67ff89f 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -4015,6 +4015,7 @@
     method public void onError(int);
     method public void onFinished();
     method public void onProgress(float);
+    field public static final int BUGREPORT_ERROR_ANOTHER_REPORT_IN_PROGRESS = 5; // 0x5
     field public static final int BUGREPORT_ERROR_INVALID_INPUT = 1; // 0x1
     field public static final int BUGREPORT_ERROR_RUNTIME = 2; // 0x2
     field public static final int BUGREPORT_ERROR_USER_CONSENT_TIMED_OUT = 4; // 0x4
@@ -5917,7 +5918,14 @@
     field public static final int VSNCP_TIMEOUT = 2236; // 0x8bc
   }
 
-  public class DisconnectCause {
+  public final class DataSpecificRegistrationStates implements android.os.Parcelable {
+    method public int describeContents();
+    method @NonNull public android.telephony.LteVopsSupportInfo getLteVopsSupportInfo();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.telephony.DataSpecificRegistrationStates> CREATOR;
+  }
+
+  public final class DisconnectCause {
     field public static final int ALREADY_DIALING = 72; // 0x48
     field public static final int ANSWERED_ELSEWHERE = 52; // 0x34
     field public static final int BUSY = 4; // 0x4
@@ -6025,6 +6033,7 @@
     method public int getAccessNetworkTechnology();
     method public int[] getAvailableServices();
     method public android.telephony.CellIdentity getCellIdentity();
+    method @Nullable public android.telephony.DataSpecificRegistrationStates getDataSpecificStates();
     method public int getDomain();
     method public int getRegState();
     method public int getRejectCause();
@@ -6095,18 +6104,18 @@
 
   public class PhoneStateListener {
     method public void onCallAttributesChanged(@NonNull android.telephony.CallAttributes);
-    method public void onCallDisconnectCauseChanged(int, int);
-    method public void onImsCallDisconnectCauseChanged(@NonNull android.telephony.ims.ImsReasonInfo);
-    method public void onPreciseCallStateChanged(android.telephony.PreciseCallState);
-    method public void onPreciseDataConnectionStateChanged(android.telephony.PreciseDataConnectionState);
+    method @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public void onCallDisconnectCauseChanged(int, int);
+    method @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public void onImsCallDisconnectCauseChanged(@NonNull android.telephony.ims.ImsReasonInfo);
+    method @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public void onPreciseCallStateChanged(@NonNull android.telephony.PreciseCallState);
+    method @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public void onPreciseDataConnectionStateChanged(android.telephony.PreciseDataConnectionState);
     method public void onRadioPowerStateChanged(int);
     method public void onSrvccStateChanged(int);
     method public void onVoiceActivationStateChanged(int);
     field public static final int LISTEN_CALL_ATTRIBUTES_CHANGED = 67108864; // 0x4000000
-    field public static final int LISTEN_CALL_DISCONNECT_CAUSES = 33554432; // 0x2000000
-    field public static final int LISTEN_IMS_CALL_DISCONNECT_CAUSES = 134217728; // 0x8000000
-    field public static final int LISTEN_PRECISE_CALL_STATE = 2048; // 0x800
-    field public static final int LISTEN_PRECISE_DATA_CONNECTION_STATE = 4096; // 0x1000
+    field @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public static final int LISTEN_CALL_DISCONNECT_CAUSES = 33554432; // 0x2000000
+    field @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public static final int LISTEN_IMS_CALL_DISCONNECT_CAUSES = 134217728; // 0x8000000
+    field @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public static final int LISTEN_PRECISE_CALL_STATE = 2048; // 0x800
+    field @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public static final int LISTEN_PRECISE_DATA_CONNECTION_STATE = 4096; // 0x1000
     field public static final int LISTEN_RADIO_POWER_STATE_CHANGED = 8388608; // 0x800000
     field @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public static final int LISTEN_SRVCC_STATE_CHANGED = 16384; // 0x4000
     field public static final int LISTEN_VOICE_ACTIVATION_STATE = 131072; // 0x20000
@@ -6141,7 +6150,7 @@
     field public static final android.os.Parcelable.Creator<android.telephony.PreciseDataConnectionState> CREATOR;
   }
 
-  public class PreciseDisconnectCause {
+  public final class PreciseDisconnectCause {
     field public static final int ACCESS_CLASS_BLOCKED = 260; // 0x104
     field public static final int ACCESS_INFORMATION_DISCARDED = 43; // 0x2b
     field public static final int ACM_LIMIT_EXCEEDED = 68; // 0x44
@@ -6358,7 +6367,7 @@
     method @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public int getRadioPowerState();
     method public int getSimApplicationState();
     method public int getSimCardState();
-    method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public String getSimLocale();
+    method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public java.util.Locale getSimLocale();
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public long getSupportedRadioAccessFamily();
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public java.util.List<android.telephony.TelephonyHistogram> getTelephonyHistograms();
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public android.telephony.UiccSlotInfo[] getUiccSlotsInfo();
@@ -6467,7 +6476,7 @@
   }
 
   public class UiccSlotInfo implements android.os.Parcelable {
-    ctor public UiccSlotInfo(boolean, boolean, String, int, int, boolean);
+    ctor @Deprecated public UiccSlotInfo(boolean, boolean, String, int, int, boolean);
     method public int describeContents();
     method public String getCardId();
     method public int getCardStateInfo();
@@ -6475,6 +6484,7 @@
     method public boolean getIsEuicc();
     method public boolean getIsExtendedApduSupported();
     method public int getLogicalSlotIdx();
+    method public boolean isRemovable();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int CARD_STATE_INFO_ABSENT = 1; // 0x1
     field public static final int CARD_STATE_INFO_ERROR = 3; // 0x3
@@ -7258,12 +7268,12 @@
     method public int describeContents();
     method public int getAudioDirection();
     method public int getAudioQuality();
-    method public boolean getRttAudioSpeech();
     method public int getRttMode();
     method public int getVideoDirection();
     method public int getVideoQuality();
+    method public boolean isReceivingRttAudio();
     method public boolean isRttCall();
-    method public void setRttAudioSpeech(boolean);
+    method public void setReceivingRttAudio(boolean);
     method public void setRttMode(int);
     method public void writeToParcel(android.os.Parcel, int);
     field public static final int AUDIO_QUALITY_AMR = 1; // 0x1
@@ -7666,7 +7676,7 @@
 
 package android.telephony.mbms.vendor {
 
-  public class MbmsDownloadServiceBase extends android.os.Binder implements android.os.IInterface {
+  public class MbmsDownloadServiceBase extends android.os.Binder {
     ctor public MbmsDownloadServiceBase();
     method public int addProgressListener(android.telephony.mbms.DownloadRequest, android.telephony.mbms.DownloadProgressListener) throws android.os.RemoteException;
     method public int addStatusListener(android.telephony.mbms.DownloadRequest, android.telephony.mbms.DownloadStatusListener) throws android.os.RemoteException;
@@ -7699,7 +7709,7 @@
     method public void updateGroupCall(int, long, java.util.List<java.lang.Integer>, java.util.List<java.lang.Integer>);
   }
 
-  public class MbmsStreamingServiceBase extends android.os.Binder implements android.os.IInterface {
+  public class MbmsStreamingServiceBase extends android.os.Binder {
     ctor public MbmsStreamingServiceBase();
     method public android.os.IBinder asBinder();
     method public void dispose(int) throws android.os.RemoteException;
diff --git a/api/test-current.txt b/api/test-current.txt
index 62ef0b0..400046b 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -1519,7 +1519,7 @@
 
 package android.telephony.mbms.vendor {
 
-  public class MbmsDownloadServiceBase extends android.os.Binder implements android.os.IInterface {
+  public class MbmsDownloadServiceBase extends android.os.Binder {
     ctor public MbmsDownloadServiceBase();
     method public int addProgressListener(android.telephony.mbms.DownloadRequest, android.telephony.mbms.DownloadProgressListener) throws android.os.RemoteException;
     method public int addStatusListener(android.telephony.mbms.DownloadRequest, android.telephony.mbms.DownloadStatusListener) throws android.os.RemoteException;
@@ -1552,7 +1552,7 @@
     method public void updateGroupCall(int, long, java.util.List<java.lang.Integer>, java.util.List<java.lang.Integer>);
   }
 
-  public class MbmsStreamingServiceBase extends android.os.Binder implements android.os.IInterface {
+  public class MbmsStreamingServiceBase extends android.os.Binder {
     ctor public MbmsStreamingServiceBase();
     method public android.os.IBinder asBinder();
     method public void dispose(int) throws android.os.RemoteException;
diff --git a/cmds/statsd/Android.bp b/cmds/statsd/Android.bp
index 5c3d17e..f178fa2 100644
--- a/cmds/statsd/Android.bp
+++ b/cmds/statsd/Android.bp
@@ -323,4 +323,8 @@
     },
 }
 
-
+// Filegroup for statsd config proto definition.
+filegroup {
+     name: "statsd-config-proto-def",
+     srcs: ["src/statsd_config.proto"],
+}
diff --git a/config/hiddenapi-greylist.txt b/config/hiddenapi-greylist.txt
index e166c31..4a43616 100644
--- a/config/hiddenapi-greylist.txt
+++ b/config/hiddenapi-greylist.txt
@@ -3018,15 +3018,8 @@
 Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->loge(Ljava/lang/String;)V
 Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mAdnCache:Lcom/android/internal/telephony/uicc/AdnRecordCache;
 Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mBaseHandler:Landroid/os/Handler;
-Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mCurrentApp:Lcom/android/internal/telephony/uicc/UiccCardApplication;
-Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mIs3gCard:Z
-Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mLock:Ljava/lang/Object;
 Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mPhone:Lcom/android/internal/telephony/Phone;
-Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mRecords:Ljava/util/List;
-Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mRecordSize:[I
-Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->mSuccess:Z
 Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->updateEfForIccType(I)I
-Lcom/android/internal/telephony/IccPhoneBookInterfaceManager;->waitForResult(Ljava/util/concurrent/atomic/AtomicBoolean;)V
 Lcom/android/internal/telephony/IccProvider;-><init>()V
 Lcom/android/internal/telephony/IccProvider;->ADDRESS_BOOK_COLUMN_NAMES:[Ljava/lang/String;
 Lcom/android/internal/telephony/IccProvider;->DBG:Z
diff --git a/core/java/android/app/timezone/RulesState.java b/core/java/android/app/timezone/RulesState.java
index e86d348..38dd1eb 100644
--- a/core/java/android/app/timezone/RulesState.java
+++ b/core/java/android/app/timezone/RulesState.java
@@ -33,7 +33,7 @@
  *
  * <p>The following properties are included:
  * <dl>
- *     <dt>systemRulesVersion</dt>
+ *     <dt>baseRulesVersion</dt>
  *     <dd>the IANA rules version that shipped with the OS. Always present. e.g. "2017a".</dd>
  *     <dt>distroFormatVersionSupported</dt>
  *     <dd>the distro format version supported by this device. Always present.</dd>
@@ -98,7 +98,7 @@
     private static final byte BYTE_FALSE = 0;
     private static final byte BYTE_TRUE = 1;
 
-    private final String mSystemRulesVersion;
+    private final String mBaseRulesVersion;
     private final DistroFormatVersion mDistroFormatVersionSupported;
     private final boolean mOperationInProgress;
     @StagedOperationType private final int mStagedOperationType;
@@ -106,13 +106,13 @@
     @DistroStatus private final int mDistroStatus;
     @Nullable private final DistroRulesVersion mInstalledDistroRulesVersion;
 
-    public RulesState(String systemRulesVersion, DistroFormatVersion distroFormatVersionSupported,
+    public RulesState(String baseRulesVersion, DistroFormatVersion distroFormatVersionSupported,
             boolean operationInProgress,
             @StagedOperationType int stagedOperationType,
             @Nullable DistroRulesVersion stagedDistroRulesVersion,
             @DistroStatus int distroStatus,
             @Nullable DistroRulesVersion installedDistroRulesVersion) {
-        this.mSystemRulesVersion = validateRulesVersion("systemRulesVersion", systemRulesVersion);
+        this.mBaseRulesVersion = validateRulesVersion("baseRulesVersion", baseRulesVersion);
         this.mDistroFormatVersionSupported =
                 validateNotNull("distroFormatVersionSupported", distroFormatVersionSupported);
         this.mOperationInProgress = operationInProgress;
@@ -132,8 +132,8 @@
                 "installedDistroRulesVersion", installedDistroRulesVersion);
     }
 
-    public String getSystemRulesVersion() {
-        return mSystemRulesVersion;
+    public String getBaseRulesVersion() {
+        return mBaseRulesVersion;
     }
 
     public boolean isOperationInProgress() {
@@ -172,14 +172,14 @@
     }
 
     /**
-     * Returns true if the system image data files contain IANA rules data that are newer than the
+     * Returns true if the base data files contain IANA rules data that are newer than the
      * distro IANA rules version supplied, i.e. true when the version specified would be "worse"
-     * than the one that is in the system image. Returns false if the system image version is the
+     * than the one that is in the base data. Returns false if the base version is the
      * same or older, i.e. false when the version specified would be "better" than the one that is
-     * in the system image.
+     * in the base set.
      */
-    public boolean isSystemVersionNewerThan(DistroRulesVersion distroRulesVersion) {
-        return mSystemRulesVersion.compareTo(distroRulesVersion.getRulesVersion()) > 0;
+    public boolean isBaseVersionNewerThan(DistroRulesVersion distroRulesVersion) {
+        return mBaseRulesVersion.compareTo(distroRulesVersion.getRulesVersion()) > 0;
     }
 
     public static final Parcelable.Creator<RulesState> CREATOR =
@@ -194,14 +194,14 @@
     };
 
     private static RulesState createFromParcel(Parcel in) {
-        String systemRulesVersion = in.readString();
+        String baseRulesVersion = in.readString();
         DistroFormatVersion distroFormatVersionSupported = in.readParcelable(null);
         boolean operationInProgress = in.readByte() == BYTE_TRUE;
         int distroStagedState = in.readByte();
         DistroRulesVersion stagedDistroRulesVersion = in.readParcelable(null);
         int installedDistroStatus = in.readByte();
         DistroRulesVersion installedDistroRulesVersion = in.readParcelable(null);
-        return new RulesState(systemRulesVersion, distroFormatVersionSupported, operationInProgress,
+        return new RulesState(baseRulesVersion, distroFormatVersionSupported, operationInProgress,
                 distroStagedState, stagedDistroRulesVersion,
                 installedDistroStatus, installedDistroRulesVersion);
     }
@@ -213,7 +213,7 @@
 
     @Override
     public void writeToParcel(Parcel out, int flags) {
-        out.writeString(mSystemRulesVersion);
+        out.writeString(mBaseRulesVersion);
         out.writeParcelable(mDistroFormatVersionSupported, 0);
         out.writeByte(mOperationInProgress ? BYTE_TRUE : BYTE_FALSE);
         out.writeByte((byte) mStagedOperationType);
@@ -242,7 +242,7 @@
         if (mDistroStatus != that.mDistroStatus) {
             return false;
         }
-        if (!mSystemRulesVersion.equals(that.mSystemRulesVersion)) {
+        if (!mBaseRulesVersion.equals(that.mBaseRulesVersion)) {
             return false;
         }
         if (!mDistroFormatVersionSupported.equals(that.mDistroFormatVersionSupported)) {
@@ -259,7 +259,7 @@
 
     @Override
     public int hashCode() {
-        int result = mSystemRulesVersion.hashCode();
+        int result = mBaseRulesVersion.hashCode();
         result = 31 * result + mDistroFormatVersionSupported.hashCode();
         result = 31 * result + (mOperationInProgress ? 1 : 0);
         result = 31 * result + mStagedOperationType;
@@ -275,7 +275,7 @@
     @Override
     public String toString() {
         return "RulesState{"
-                + "mSystemRulesVersion='" + mSystemRulesVersion + '\''
+                + "mBaseRulesVersion='" + mBaseRulesVersion + '\''
                 + ", mDistroFormatVersionSupported=" + mDistroFormatVersionSupported
                 + ", mOperationInProgress=" + mOperationInProgress
                 + ", mStagedOperationType=" + mStagedOperationType
diff --git a/core/java/android/net/SSLCertificateSocketFactory.java b/core/java/android/net/SSLCertificateSocketFactory.java
index 90dccb5..45860b3 100644
--- a/core/java/android/net/SSLCertificateSocketFactory.java
+++ b/core/java/android/net/SSLCertificateSocketFactory.java
@@ -23,8 +23,7 @@
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.os.RoSystemProperties;
-import com.android.org.conscrypt.Conscrypt;
-import com.android.org.conscrypt.OpenSSLContextImpl;
+import com.android.org.conscrypt.ClientSessionContext;
 import com.android.org.conscrypt.OpenSSLSocketImpl;
 import com.android.org.conscrypt.SSLClientSessionCache;
 
@@ -33,6 +32,8 @@
 import java.net.Socket;
 import java.net.SocketException;
 import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
 import java.security.PrivateKey;
 import java.security.cert.X509Certificate;
 
@@ -40,6 +41,7 @@
 import javax.net.ssl.HostnameVerifier;
 import javax.net.ssl.HttpsURLConnection;
 import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLException;
 import javax.net.ssl.SSLPeerUnverifiedException;
 import javax.net.ssl.SSLSession;
@@ -251,11 +253,12 @@
     private SSLSocketFactory makeSocketFactory(
             KeyManager[] keyManagers, TrustManager[] trustManagers) {
         try {
-            OpenSSLContextImpl sslContext =  (OpenSSLContextImpl) Conscrypt.newPreferredSSLContextSpi();
-            sslContext.engineInit(keyManagers, trustManagers, null);
-            sslContext.engineGetClientSessionContext().setPersistentCache(mSessionCache);
-            return sslContext.engineGetSocketFactory();
-        } catch (KeyManagementException e) {
+            SSLContext sslContext = SSLContext.getInstance("TLS", "AndroidOpenSSL");
+            sslContext.init(keyManagers, trustManagers, null);
+            ((ClientSessionContext) sslContext.getClientSessionContext())
+                .setPersistentCache(mSessionCache);
+            return sslContext.getSocketFactory();
+        } catch (KeyManagementException | NoSuchAlgorithmException | NoSuchProviderException e) {
             Log.wtf(TAG, e);
             return (SSLSocketFactory) SSLSocketFactory.getDefault();  // Fallback
         }
diff --git a/core/java/android/net/VpnService.java b/core/java/android/net/VpnService.java
index 784f233..ebb1ae4 100644
--- a/core/java/android/net/VpnService.java
+++ b/core/java/android/net/VpnService.java
@@ -19,6 +19,7 @@
 import static android.system.OsConstants.AF_INET;
 import static android.system.OsConstants.AF_INET6;
 
+import android.annotation.NonNull;
 import android.annotation.RequiresPermission;
 import android.annotation.SystemApi;
 import android.annotation.UnsupportedAppUsage;
@@ -512,7 +513,7 @@
          * Sets an HTTP proxy for the VPN network. This proxy is only a recommendation
          * and it is possible that some apps will ignore it.
          */
-        public Builder setHttpProxy(ProxyInfo proxyInfo) {
+        public Builder setHttpProxy(@NonNull ProxyInfo proxyInfo) {
             mConfig.proxyInfo = proxyInfo;
             return this;
         }
diff --git a/core/java/android/net/metrics/ValidationProbeEvent.java b/core/java/android/net/metrics/ValidationProbeEvent.java
index 42e8aa6..a43dc60 100644
--- a/core/java/android/net/metrics/ValidationProbeEvent.java
+++ b/core/java/android/net/metrics/ValidationProbeEvent.java
@@ -79,7 +79,7 @@
     }
 
     /**
-     * Utility to create an instance of {@link ApfProgramEvent}.
+     * Utility to create an instance of {@link ValidationProbeEvent}.
      */
     public static class Builder {
         private long mDurationMs;
diff --git a/core/java/android/os/BugreportManager.java b/core/java/android/os/BugreportManager.java
index 27f7e22..684369a 100644
--- a/core/java/android/os/BugreportManager.java
+++ b/core/java/android/os/BugreportManager.java
@@ -59,7 +59,8 @@
                 BUGREPORT_ERROR_INVALID_INPUT,
                 BUGREPORT_ERROR_RUNTIME,
                 BUGREPORT_ERROR_USER_DENIED_CONSENT,
-                BUGREPORT_ERROR_USER_CONSENT_TIMED_OUT
+                BUGREPORT_ERROR_USER_CONSENT_TIMED_OUT,
+                BUGREPORT_ERROR_ANOTHER_REPORT_IN_PROGRESS
         })
 
         /** Possible error codes taking a bugreport can encounter */
@@ -81,6 +82,10 @@
         public static final int BUGREPORT_ERROR_USER_CONSENT_TIMED_OUT =
                 IDumpstateListener.BUGREPORT_ERROR_USER_CONSENT_TIMED_OUT;
 
+        /** There is currently a bugreport running. The caller should try again later. */
+        public static final int BUGREPORT_ERROR_ANOTHER_REPORT_IN_PROGRESS =
+                IDumpstateListener.BUGREPORT_ERROR_ANOTHER_REPORT_IN_PROGRESS;
+
         /**
          * Called when there is a progress update.
          * @param progress the progress in [0.0, 100.0]
@@ -96,6 +101,9 @@
          * <p>If {@code BUGREPORT_ERROR_USER_CONSENT_TIMED_OUT} is passed, then the consent timed
          * out, but the bugreport could be available in the internal directory of dumpstate for
          * manual retrieval.
+         *
+         * <p> If {@code BUGREPORT_ERROR_ANOTHER_REPORT_IN_PROGRESS} is passed, then the
+         * caller should try later, as only one bugreport can be in progress at a time.
          */
         public void onError(@BugreportErrorCode int errorCode) {}
 
diff --git a/core/java/android/provider/CallLog.java b/core/java/android/provider/CallLog.java
index f63c0adb..44adc1c 100644
--- a/core/java/android/provider/CallLog.java
+++ b/core/java/android/provider/CallLog.java
@@ -783,7 +783,7 @@
                 String postDialDigits, String viaNumber, int presentation, int callType,
                 int features, PhoneAccountHandle accountHandle, long start, int duration,
                 Long dataUsage, boolean addForAllUsers, UserHandle userToBeInsertedTo,
-                boolean isRead, int callBlockReason, String callScreeningAppName,
+                boolean isRead, int callBlockReason, CharSequence callScreeningAppName,
                 String callScreeningComponentName, CallIdentification callIdentification) {
             if (VERBOSE_LOG) {
                 Log.v(LOG_TAG, String.format("Add call: number=%s, user=%s, for all=%s",
@@ -836,15 +836,19 @@
             }
 
             values.put(BLOCK_REASON, callBlockReason);
-            values.put(CALL_SCREENING_APP_NAME, callScreeningAppName);
+            values.put(CALL_SCREENING_APP_NAME, charSequenceToString(callScreeningAppName));
             values.put(CALL_SCREENING_COMPONENT_NAME, callScreeningComponentName);
 
             if (callIdentification != null) {
                 values.put(CALL_ID_PACKAGE_NAME, callIdentification.getCallScreeningPackageName());
-                values.put(CALL_ID_APP_NAME, callIdentification.getCallScreeningAppName());
-                values.put(CALL_ID_NAME, callIdentification.getName());
-                values.put(CALL_ID_DESCRIPTION, callIdentification.getDescription());
-                values.put(CALL_ID_DETAILS, callIdentification.getDetails());
+                values.put(CALL_ID_APP_NAME,
+                        charSequenceToString(callIdentification.getCallScreeningAppName()));
+                values.put(CALL_ID_NAME,
+                        charSequenceToString(callIdentification.getName()));
+                values.put(CALL_ID_DESCRIPTION,
+                        charSequenceToString(callIdentification.getDescription()));
+                values.put(CALL_ID_DETAILS,
+                        charSequenceToString(callIdentification.getDetails()));
                 values.put(CALL_ID_NUISANCE_CONFIDENCE, callIdentification.getNuisanceConfidence());
             } else {
                 values.putNull(CALL_ID_PACKAGE_NAME);
@@ -987,6 +991,10 @@
             return result;
         }
 
+        private static String charSequenceToString(CharSequence sequence) {
+            return sequence == null ? null : sequence.toString();
+        }
+
         /** @hide */
         public static boolean shouldHaveSharedCallLogEntries(Context context,
                 UserManager userManager, int userId) {
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 798401d..3fe06f1 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -4818,11 +4818,8 @@
         protected int onProcess(QueuedInputEvent q) {
             if (q.mEvent instanceof KeyEvent) {
                 return processKeyEvent(q);
-            } else {
-                final int source = q.mEvent.getSource();
-                if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
-                    return processPointerEvent(q);
-                }
+            } else if (q.mEvent instanceof MotionEvent) {
+                return processMotionEvent(q);
             }
             return FORWARD;
         }
@@ -4846,6 +4843,23 @@
             return FORWARD;
         }
 
+        private int processMotionEvent(QueuedInputEvent q) {
+            final MotionEvent event = (MotionEvent) q.mEvent;
+
+            if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
+                return processPointerEvent(q);
+            }
+
+            // If the motion event is from an absolute position device, exit touch mode
+            final int action = event.getActionMasked();
+            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
+                if (event.isFromSource(InputDevice.SOURCE_CLASS_POSITION)) {
+                    ensureTouchMode(false);
+                }
+            }
+            return FORWARD;
+        }
+
         private int processPointerEvent(QueuedInputEvent q) {
             final MotionEvent event = (MotionEvent)q.mEvent;
 
@@ -5178,6 +5192,12 @@
         private int processGenericMotionEvent(QueuedInputEvent q) {
             final MotionEvent event = (MotionEvent)q.mEvent;
 
+            if (event.isFromSource(InputDevice.SOURCE_TOUCHPAD)) {
+                if (hasPointerCapture() && mView.dispatchCapturedPointerEvent(event)) {
+                    return FINISH_HANDLED;
+                }
+            }
+
             // Deliver the event to the view.
             if (mView.dispatchGenericMotionEvent(event)) {
                 return FINISH_HANDLED;
diff --git a/core/jni/Android.bp b/core/jni/Android.bp
index c385ca1..f9813fd 100644
--- a/core/jni/Android.bp
+++ b/core/jni/Android.bp
@@ -290,6 +290,7 @@
         "libhwui",
         "libdl",
         "libstatslog",
+        "server_configurable_flags",
     ],
 
     generated_sources: ["android_util_StatsLog.cpp"],
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index 565fa6f..388285a 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -31,6 +31,7 @@
 #include <binder/Parcel.h>
 #include <utils/threads.h>
 #include <cutils/properties.h>
+#include <server_configurable_flags/get_flags.h>
 
 #include <SkGraphics.h>
 
@@ -219,6 +220,23 @@
 extern int register_com_android_internal_os_ZygoteInit(JNIEnv *env);
 extern int register_com_android_internal_util_VirtualRefBasePtr(JNIEnv *env);
 
+// Namespace for Android Runtime flags applied during boot time.
+static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
+// Feature flag name to enable/disable generational garbage collection in ART's
+// Concurrent Copying (CC) garbage collector.
+static const char* ENABLE_GENERATIONAL_CC = "enable_generational_cc";
+// Runtime option enabling generational garbage collection in ART's Concurrent
+// Copying (CC) garbage collector.
+static const char* kGenerationalCCRuntimeOption = "-Xgc:generational_cc";
+// Runtime option disabling generational garbage collection in ART's Concurrent
+// Copying (CC) garbage collector.
+static const char* kNoGenerationalCCRuntimeOption = "-Xgc:nogenerational_cc";
+
+// Feature flag name for running the JIT in Zygote experiment, b/119800099.
+static const char* ENABLE_APEX_IMAGE = "enable_apex_image";
+// Flag to pass to the runtime when using the apex image.
+static const char* kApexImageOption = "-Ximage:/system/framework/apex.art";
+
 static AndroidRuntime* gCurRuntime = NULL;
 
 /*
@@ -653,8 +671,17 @@
     char jdwpProviderBuf[sizeof("-XjdwpProvider:") - 1 + PROPERTY_VALUE_MAX];
     char bootImageBuf[sizeof("-Ximage:") - 1 + PROPERTY_VALUE_MAX];
 
-    if (parseRuntimeOption("dalvik.vm.boot-image", bootImageBuf, "-Ximage:")) {
-        ALOGI("Boot image: '%s'\n", bootImageBuf);
+    std::string use_apex_image =
+        server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
+                                                             ENABLE_APEX_IMAGE,
+                                                             /*default_value=*/ "");
+    if (use_apex_image == "true") {
+        addOption(kApexImageOption);
+        ALOGI("Using Apex boot image: '%s'\n", kApexImageOption);
+    } else if (parseRuntimeOption("dalvik.vm.boot-image", bootImageBuf, "-Ximage:")) {
+        ALOGI("Using dalvik.vm.boot-image: '%s'\n", bootImageBuf);
+    } else {
+        ALOGI("Using default boot image");
     }
 
     bool checkJni = false;
@@ -769,7 +796,23 @@
       addOption("-XX:LowMemoryMode");
     }
 
+    /*
+     * Garbage-collection related options.
+     */
     parseRuntimeOption("dalvik.vm.gctype", gctypeOptsBuf, "-Xgc:");
+
+    // If it set, honor the "enable_generational_cc" device configuration;
+    // otherwise, let the runtime use its default behavior.
+    std::string enable_generational_cc =
+        server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
+                                                             ENABLE_GENERATIONAL_CC,
+                                                             /*default_value=*/ "");
+    if (enable_generational_cc == "true") {
+        addOption(kGenerationalCCRuntimeOption);
+    } else if (enable_generational_cc == "false") {
+        addOption(kNoGenerationalCCRuntimeOption);
+    }
+
     parseRuntimeOption("dalvik.vm.backgroundgctype", backgroundgcOptsBuf, "-XX:BackgroundGC=");
 
     /*
diff --git a/core/jni/android_net_LocalSocketImpl.cpp b/core/jni/android_net_LocalSocketImpl.cpp
index a1f2377..1163b86 100644
--- a/core/jni/android_net_LocalSocketImpl.cpp
+++ b/core/jni/android_net_LocalSocketImpl.cpp
@@ -33,14 +33,16 @@
 #include <unistd.h>
 #include <sys/ioctl.h>
 
+#include <android-base/cmsg.h>
+#include <android-base/macros.h>
 #include <cutils/sockets.h>
 #include <netinet/tcp.h>
 #include <nativehelper/ScopedUtfChars.h>
 
-namespace android {
+using android::base::ReceiveFileDescriptorVector;
+using android::base::SendFileDescriptorVector;
 
-template <typename T>
-void UNUSED(T t) {}
+namespace android {
 
 static jfieldID field_inboundFileDescriptors;
 static jfieldID field_outboundFileDescriptors;
@@ -118,67 +120,6 @@
 }
 
 /**
- * Processes ancillary data, handling only
- * SCM_RIGHTS. Creates appropriate objects and sets appropriate
- * fields in the LocalSocketImpl object. Returns 0 on success
- * or -1 if an exception was thrown.
- */
-static int socket_process_cmsg(JNIEnv *env, jobject thisJ, struct msghdr * pMsg)
-{
-    struct cmsghdr *cmsgptr;
-
-    for (cmsgptr = CMSG_FIRSTHDR(pMsg);
-            cmsgptr != NULL; cmsgptr = CMSG_NXTHDR(pMsg, cmsgptr)) {
-
-        if (cmsgptr->cmsg_level != SOL_SOCKET) {
-            continue;
-        }
-
-        if (cmsgptr->cmsg_type == SCM_RIGHTS) {
-            int *pDescriptors = (int *)CMSG_DATA(cmsgptr);
-            jobjectArray fdArray;
-            int count
-                = ((cmsgptr->cmsg_len - CMSG_LEN(0)) / sizeof(int));
-
-            if (count < 0) {
-                jniThrowException(env, "java/io/IOException",
-                    "invalid cmsg length");
-                return -1;
-            }
-
-            fdArray = env->NewObjectArray(count, class_FileDescriptor, NULL);
-
-            if (fdArray == NULL) {
-                return -1;
-            }
-
-            for (int i = 0; i < count; i++) {
-                jobject fdObject
-                        = jniCreateFileDescriptor(env, pDescriptors[i]);
-
-                if (env->ExceptionCheck()) {
-                    return -1;
-                }
-
-                env->SetObjectArrayElement(fdArray, i, fdObject);
-
-                if (env->ExceptionCheck()) {
-                    return -1;
-                }
-            }
-
-            env->SetObjectField(thisJ, field_inboundFileDescriptors, fdArray);
-
-            if (env->ExceptionCheck()) {
-                return -1;
-            }
-        }
-    }
-
-    return 0;
-}
-
-/**
  * Reads data from a socket into buf, processing any ancillary data
  * and adding it to thisJ.
  *
@@ -189,47 +130,48 @@
         void *buffer, size_t len)
 {
     ssize_t ret;
-    struct msghdr msg;
-    struct iovec iv;
-    unsigned char *buf = (unsigned char *)buffer;
-    // Enough buffer for a pile of fd's. We throw an exception if
-    // this buffer is too small.
-    struct cmsghdr cmsgbuf[2*sizeof(cmsghdr) + 0x100];
+    std::vector<android::base::unique_fd> received_fds;
 
-    memset(&msg, 0, sizeof(msg));
-    memset(&iv, 0, sizeof(iv));
-
-    iv.iov_base = buf;
-    iv.iov_len = len;
-
-    msg.msg_iov = &iv;
-    msg.msg_iovlen = 1;
-    msg.msg_control = cmsgbuf;
-    msg.msg_controllen = sizeof(cmsgbuf);
-
-    ret = TEMP_FAILURE_RETRY(recvmsg(fd, &msg, MSG_NOSIGNAL | MSG_CMSG_CLOEXEC));
-
-    if (ret < 0 && errno == EPIPE) {
-        // Treat this as an end of stream
-        return 0;
-    }
+    ret = ReceiveFileDescriptorVector(fd, buffer, len, 64, &received_fds);
 
     if (ret < 0) {
+        if (errno == EPIPE) {
+            // Treat this as an end of stream
+            return 0;
+        }
+
         jniThrowIOException(env, errno);
         return -1;
     }
 
-    if ((msg.msg_flags & (MSG_CTRUNC | MSG_OOB | MSG_ERRQUEUE)) != 0) {
-        // To us, any of the above flags are a fatal error
+    if (received_fds.size() > 0) {
+        jobjectArray fdArray = env->NewObjectArray(received_fds.size(), class_FileDescriptor, NULL);
 
-        jniThrowException(env, "java/io/IOException",
-                "Unexpected error or truncation during recvmsg()");
+        if (fdArray == NULL) {
+            // NewObjectArray has thrown.
+            return -1;
+        }
 
-        return -1;
-    }
+        for (size_t i = 0; i < received_fds.size(); i++) {
+            jobject fdObject = jniCreateFileDescriptor(env, received_fds[i].get());
 
-    if (ret >= 0) {
-        socket_process_cmsg(env, thisJ, &msg);
+            if (env->ExceptionCheck()) {
+                return -1;
+            }
+
+            env->SetObjectArrayElement(fdArray, i, fdObject);
+
+            if (env->ExceptionCheck()) {
+                return -1;
+            }
+        }
+
+        for (auto &fd : received_fds) {
+            // The fds are stored in java.io.FileDescriptors now.
+            static_cast<void>(fd.release());
+        }
+
+        env->SetObjectField(thisJ, field_inboundFileDescriptors, fdArray);
     }
 
     return ret;
@@ -243,7 +185,6 @@
 static int socket_write_all(JNIEnv *env, jobject object, int fd,
         void *buf, size_t len)
 {
-    ssize_t ret;
     struct msghdr msg;
     unsigned char *buffer = (unsigned char *)buf;
     memset(&msg, 0, sizeof(msg));
@@ -256,14 +197,11 @@
         return -1;
     }
 
-    struct cmsghdr *cmsg;
     int countFds = outboundFds == NULL ? 0 : env->GetArrayLength(outboundFds);
-    int fds[countFds];
-    char msgbuf[CMSG_SPACE(countFds)];
+    std::vector<int> fds;
 
     // Add any pending outbound file descriptors to the message
     if (outboundFds != NULL) {
-
         if (env->ExceptionCheck()) {
             return -1;
         }
@@ -274,47 +212,25 @@
                 return -1;
             }
 
-            fds[i] = jniGetFDFromFileDescriptor(env, fdObject);
+            fds.push_back(jniGetFDFromFileDescriptor(env, fdObject));
             if (env->ExceptionCheck()) {
                 return -1;
             }
         }
-
-        // See "man cmsg" really
-        msg.msg_control = msgbuf;
-        msg.msg_controllen = sizeof msgbuf;
-        cmsg = CMSG_FIRSTHDR(&msg);
-        cmsg->cmsg_level = SOL_SOCKET;
-        cmsg->cmsg_type = SCM_RIGHTS;
-        cmsg->cmsg_len = CMSG_LEN(sizeof fds);
-        memcpy(CMSG_DATA(cmsg), fds, sizeof fds);
     }
 
-    // We only write our msg_control during the first write
-    while (len > 0) {
-        struct iovec iv;
-        memset(&iv, 0, sizeof(iv));
+    ssize_t rc = SendFileDescriptorVector(fd, buffer, len, fds);
 
-        iv.iov_base = buffer;
-        iv.iov_len = len;
-
-        msg.msg_iov = &iv;
-        msg.msg_iovlen = 1;
-
-        do {
-            ret = sendmsg(fd, &msg, MSG_NOSIGNAL);
-        } while (ret < 0 && errno == EINTR);
-
-        if (ret < 0) {
+    while (rc != len) {
+        if (rc == -1) {
             jniThrowIOException(env, errno);
             return -1;
         }
 
-        buffer += ret;
-        len -= ret;
+        buffer += rc;
+        len -= rc;
 
-        // Wipes out any msg_control too
-        memset(&msg, 0, sizeof(msg));
+        rc = send(fd, buffer, len, MSG_NOSIGNAL);
     }
 
     return 0;
diff --git a/core/jni/com_android_internal_os_Zygote.cpp b/core/jni/com_android_internal_os_Zygote.cpp
index bc1332a..8216b61 100644
--- a/core/jni/com_android_internal_os_Zygote.cpp
+++ b/core/jni/com_android_internal_os_Zygote.cpp
@@ -892,6 +892,8 @@
 
     // Turn fdsan back on.
     android_fdsan_set_error_level(fdsan_error_level);
+  } else {
+    ALOGD("Forked child process %d", pid);
   }
 
   // We blocked SIGCHLD prior to a fork, we unblock it here.
diff --git a/core/jni/runtime_native_boot-flags-test.sh b/core/jni/runtime_native_boot-flags-test.sh
new file mode 100755
index 0000000..01f37f0
--- /dev/null
+++ b/core/jni/runtime_native_boot-flags-test.sh
@@ -0,0 +1,246 @@
+#!/bin/bash
+
+# Copyright (C) 2019 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Test Android Runtime (Boot) device configuration flags (living in namespace
+# `runtime_native_boot`).
+
+me=$(basename $0)
+
+# Namespace containing the tested flag.
+namespace=runtime_native_boot
+# Default set of checked zygote processes.
+zygotes=
+
+# Status of whole test script.
+exit_status=0
+
+function say {
+  echo "$me: $*"
+}
+
+function banner {
+  local separator=$(echo "$@" | sed s/./=/g )
+  say "$separator"
+  say "$@"
+  say "$separator"
+}
+
+function fail {
+  say "FAILED: $@"
+  exit_status=1
+}
+
+function reboot_and_wait_for_device {
+  say "Rebooting device..."
+  adb reboot
+  adb wait-for-device >/dev/null
+  # Wait until the device has finished booting. Give the device 60 iterations
+  # (~60 seconds) to try and finish booting before declaring defeat.
+  local niters=60
+  for i in $(seq $niters); do
+    [[ $(adb shell getprop sys.boot_completed) -eq 1 ]] && return 0
+    sleep 1
+  done
+  fail "Device did not finish booting before timeout (~$niters seconds)"
+}
+
+# check_device_config_flag CONTEXT FLAG VALUE
+# -------------------------------------------
+# Check that the device configuration flag FLAG is set to VALUE. Use CONTEXT in
+# logging.
+function check_device_config_flag {
+  local context=$1
+  local flag=$2
+  local value=$3
+
+  say "[$context] Check that the device configuration flag is set..."
+  local flag_value=$(adb shell device_config get "$namespace" "$flag")
+  [[ "$flag_value" = "$value" ]] \
+    || fail "Device configuration flag \`$flag\` set to \`$flag_value\` (expected \`$value\`)"
+}
+
+# check_no_device_config_flag CONTEXT FLAG
+# ----------------------------------------
+# Check that the device configuration flag FLAG is not set. Use CONTEXT in
+# logging.
+function check_no_device_config_flag {
+  local context=$1
+  local flag=$2
+
+  say "[$context] Check that the device configuration flag is not set..."
+  local flag_value=$(adb shell device_config get "$namespace" "$flag")
+  [[ "$flag_value" = null ]] \
+    || fail "Device configuration flag \`$flag\` set to \`$flag_value\` (expected `null`)"
+}
+
+# get_system_property PROP
+# ------------------------
+# Get system property PROP associated with a device configuration flag.
+function get_system_property {
+  local prop=$1
+
+  # Note that we need to be root to read that system property.
+  adb root >/dev/null
+  local prop_value=$(adb shell getprop "$prop")
+  adb unroot >/dev/null
+  echo "$prop_value"
+}
+
+# check_system_property CONTEXT PROP VALUE
+# ----------------------------------------
+# Check that the system property PROP associated with a device configuration
+# flag is set to VALUE. Use CONTEXT in logging.
+function check_system_property {
+  local context=$1
+  local prop=$2
+  local value=$3
+
+  say "[$context] Check that the persistent system property is set..."
+  local prop_value=$(get_system_property "$prop")
+  [[ "$prop_value" = "$value" ]] \
+    || fail "System property \`$prop\` set to \`$prop_value\` (expected \`$value\`)"
+}
+
+# check_no_system_property CONTEXT PROP
+# -------------------------------------
+# Check that the system property PROP associated with a device configuration
+# flag is not set. Use CONTEXT in logging.
+function check_no_system_property {
+  local context=$1
+  local prop=$2
+
+  say "[$context] Check that the persistent system property is not set..."
+  local prop_value=$(get_system_property "$prop")
+  [[ -z "$prop_value" ]] \
+    || fail "System property \`$prop\` set to \`$prop_value\` (expected unset property)"
+}
+
+# find_zygote_runtime_option ZYGOTE RUNTIME_OPTION
+# ------------------------------------------------
+# Return whether ZYGOTE is passed RUNTIME_OPTION.
+function find_zygote_runtime_option {
+  local zygote=$1
+  local runtime_option=$2
+
+  adb logcat -d -s "$zygote" | grep -q -e "option\[[0-9]\+\]=$runtime_option"
+}
+
+# check_zygote_gc_runtime_option CONTEXT VALUE
+# --------------------------------------------
+# Check that all zygote processes are passed device configuration flag VALUE as
+# GC runtime option. Use CONTEXT in logging.
+function check_zygote_gc_runtime_option {
+  local context=$1
+  local value=$2
+
+  say \
+    "[$context] Check that all zygote processes are passed the flag value as a GC runtime option..."
+  local runtime_option="-Xgc:$value"
+  for zygote in $zygotes; do
+    find_zygote_runtime_option "$zygote" "$runtime_option"\
+      || fail "Found no \`$runtime_option\` among runtime options passed to \`$zygote\`"
+  done
+}
+
+# check_no_zygote_gc_runtime_option CONTEXT VALUE
+# -----------------------------------------------
+# Check that no zygote process is passed device configuration flag VALUE as GC
+# runtime option.  Use CONTEXT in logging.
+function check_no_zygote_gc_runtime_option {
+  local context=$1
+  local value=$2
+
+  say "[$context] Check no zygote process is passed the flag value as a GC runtime option..."
+  local runtime_option="-Xgc:$value"
+  for zygote in $zygotes; do
+    find_zygote_runtime_option "$zygote" "$runtime_option"\
+      && fail "Found \`$runtime_option\` among runtime options passed to \`$zygote\`"
+  done
+}
+
+# test_android_runtime_flag FLAG VALUE GC_RUNTIME_OPTION
+# ------------------------------------------------------
+# Test device configuration FLAG with VALUE. Check that GC_RUNTIME_OPTION is
+# passed as GC Runtime option by the zygote.
+function test_android_runtime_flag {
+  local flag=$1
+  local value=$2
+  local gc_runtime_option=$3
+
+  # Persistent system property (set after a reboot) associated with the device
+  # configuration flag.
+  local prop="persist.device_config.$namespace.$flag"
+
+  banner "Testing \`$flag\` value \`$value\`."
+
+  say "Setting device configuration flag..."
+  adb shell device_config put "$namespace" "$flag" "$value"
+  # Give some time to the device to digest this change before rebooting.
+  sleep 3
+
+  # Check that both the device configuration flag and the associated system
+  # property are set, but that the zygote hasn't had the flag passed to it as a
+  # GC runtime option (as we haven't rebooted yet).
+  local context="Flag set, before reboot"
+  check_device_config_flag "$context" "$flag" "$value"
+  check_system_property "$context" "$prop" "$value"
+  check_no_zygote_gc_runtime_option "$context" "$gc_runtime_option"
+
+  # Reboot device for the flag value to take effect.
+  reboot_and_wait_for_device
+  context="Flag set, after 1st reboot"
+  check_device_config_flag "$context" "$flag" "$value"
+  check_system_property "$context" "$prop" "$value"
+  check_zygote_gc_runtime_option "$context" "$gc_runtime_option"
+
+  # Reboot device a second time and check that the state has persisted.
+  reboot_and_wait_for_device
+  context="Flag set, after 2nd reboot"
+  check_device_config_flag "$context" "$flag" "$value"
+  check_system_property "$context" "$prop" "$value"
+  check_zygote_gc_runtime_option "$context" "$gc_runtime_option"
+
+  say "Unsetting device configuration flag..."
+  adb shell device_config delete "$namespace" "$flag" >/dev/null
+  # Give some time to the device to digest this change before rebooting.
+  sleep 3
+
+  # Reboot and check that the device is back to its default state.
+  reboot_and_wait_for_device
+  context="Flag unset, after 3rd reboot"
+  check_no_device_config_flag "$context" "$flag"
+  check_no_system_property "$context" "$prop"
+  check_no_zygote_gc_runtime_option "$context" "$gc_runtime_option"
+}
+
+# Enumerate Zygote processes.
+case $(adb shell getprop ro.zygote) in
+  (zygote32) zygotes="zygote";;
+  (zygote64) zygotes="zygote64";;
+  (zygote32_64|zygote64_32) zygotes="zygote zygote64";;
+esac
+
+# Test "enable_generational_cc" flag values.
+test_android_runtime_flag enable_generational_cc false nogenerational_cc
+test_android_runtime_flag enable_generational_cc true generational_cc
+
+if [[ "$exit_status" -eq 0 ]]; then
+  banner "All tests passed."
+else
+  banner "Test(s) failed."
+fi
+exit $exit_status
diff --git a/core/res/res/values/arrays.xml b/core/res/res/values/arrays.xml
index 733878b..8f2d6c3 100644
--- a/core/res/res/values/arrays.xml
+++ b/core/res/res/values/arrays.xml
@@ -185,4 +185,20 @@
         <item>@string/app_info</item>
     </string-array>
 
+    <!-- Device-specific array of SIM slot indexes which are are embedded eUICCs.
+         e.g. If a device has two physical slots with indexes 0, 1, and slot 1 is an
+         eUICC, then the value of this array should be:
+             <integer-array name="non_removable_euicc_slots">
+                 <item>1</item>
+             </integer-array>
+         If a device has three physical slots and slot 1 and 2 are eUICCs, then the value of
+         this array should be:
+             <integer-array name="non_removable_euicc_slots">
+                <item>1</item>
+                <item>2</item>
+             </integer-array>
+         This is used to differentiate between removable eUICCs and built in eUICCs, and should
+         be set by OEMs for devices which use eUICCs. -->
+    <integer-array name="non_removable_euicc_slots"></integer-array>
+
 </resources>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 76791fd..a69914b 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -2844,6 +2844,8 @@
   <java-symbol type="array" name="resolver_target_actions_pin" />
   <java-symbol type="array" name="resolver_target_actions_unpin" />
 
+  <java-symbol type="array" name="non_removable_euicc_slots" />
+
   <java-symbol type="string" name="install_carrier_app_notification_title" />
   <java-symbol type="string" name="install_carrier_app_notification_text" />
   <java-symbol type="string" name="install_carrier_app_notification_text_app_name" />
diff --git a/core/tests/coretests/Android.bp b/core/tests/coretests/Android.bp
new file mode 100644
index 0000000..a909487
--- /dev/null
+++ b/core/tests/coretests/Android.bp
@@ -0,0 +1,110 @@
+android_test {
+    name: "FrameworksCoreTests",
+
+    srcs: [
+        "src/**/*.java",
+        "src/**/I*.aidl",
+        "DisabledTestApp/src/**/*.java",
+        "EnabledTestApp/src/**/*.java",
+        "BinderProxyCountingTestApp/src/**/*.java",
+        "BinderProxyCountingTestService/src/**/*.java",
+        "aidl/**/I*.aidl",
+    ],
+
+    aidl: {
+        local_include_dirs: ["aidl"],
+    },
+
+    dxflags: ["--core-library"],
+
+    aaptflags: [
+        "-0 .dat",
+        "-0 .gld",
+        "-c fa",
+    ],
+    static_libs: [
+        "frameworks-base-testutils",
+        "core-tests-support",
+        "android-common",
+        "frameworks-core-util-lib",
+        "mockwebserver",
+        "guava",
+        "android-support-test",
+        "mockito-target-minus-junit4",
+        "espresso-core",
+        "ub-uiautomator",
+        "platform-test-annotations",
+        "compatibility-device-util",
+        "truth-prebuilt",
+        "print-test-util-lib",
+    ],
+
+    libs: [
+        "android.test.runner",
+        "telephony-common",
+        "org.apache.http.legacy",
+        "android.test.base",
+        "android.test.mock",
+        "framework-atb-backward-compatibility",
+    ],
+
+    platform_apis: true,
+    test_suites: ["device-tests"],
+
+    certificate: "platform",
+
+    resource_dirs: ["res"],
+    resource_zips: [":FrameworksCoreTests_apks_as_resources"],
+}
+
+// Rules to copy all the test apks to the intermediate raw resource directory
+java_genrule {
+    name: "FrameworksCoreTests_apks_as_resources",
+    srcs: [
+        ":FrameworksCoreTests_install",
+        ":FrameworksCoreTests_install_bad_dex",
+        ":FrameworksCoreTests_install_complete_package_info",
+        ":FrameworksCoreTests_install_decl_perm",
+        ":FrameworksCoreTests_install_jni_lib_open_from_apk",
+        ":FrameworksCoreTests_install_loc_auto",
+        ":FrameworksCoreTests_install_loc_internal",
+        ":FrameworksCoreTests_install_loc_sdcard",
+        ":FrameworksCoreTests_install_loc_unspecified",
+        ":FrameworksCoreTests_install_multi_package",
+        ":FrameworksCoreTests_install_split_base",
+        ":FrameworksCoreTests_install_split_feature_a",
+        ":FrameworksCoreTests_install_use_perm_good",
+        ":FrameworksCoreTests_install_uses_feature",
+        ":FrameworksCoreTests_install_verifier_bad",
+        ":FrameworksCoreTests_install_verifier_good",
+        ":FrameworksCoreTests_keyset_permdef_sa_unone",
+        ":FrameworksCoreTests_keyset_permuse_sa_ua_ub",
+        ":FrameworksCoreTests_keyset_permuse_sb_ua_ub",
+        ":FrameworksCoreTests_keyset_sab_ua",
+        ":FrameworksCoreTests_keyset_sa_ua",
+        ":FrameworksCoreTests_keyset_sa_uab",
+        ":FrameworksCoreTests_keyset_sa_ua_ub",
+        ":FrameworksCoreTests_keyset_sa_ub",
+        ":FrameworksCoreTests_keyset_sa_unone",
+        ":FrameworksCoreTests_keyset_sau_ub",
+        ":FrameworksCoreTests_keyset_sb_ua",
+        ":FrameworksCoreTests_keyset_sb_ub",
+        ":FrameworksCoreTests_keyset_splata_api",
+        ":FrameworksCoreTests_keyset_splat_api",
+        ":FrameworksCoreTests_locales",
+        ":FrameworksCoreTests_version_1",
+        ":FrameworksCoreTests_version_1_diff",
+        ":FrameworksCoreTests_version_1_nosys",
+        ":FrameworksCoreTests_version_2",
+        ":FrameworksCoreTests_version_2_diff",
+        ":FrameworksCoreTests_version_3",
+    ],
+    out: ["FrameworkCoreTests_apks_as_resources.res.zip"],
+    tools: ["soong_zip"],
+
+    cmd: "mkdir -p $(genDir)/res/raw && " +
+        "for i in $(in); do " +
+        "  x=$${i##*FrameworksCoreTests_}; echo $${x}; cp $$i $(genDir)/res/raw/$${x%.apk};" +
+        "done && " +
+        "$(location soong_zip) -o $(out) -C $(genDir)/res -D $(genDir)/res",
+}
diff --git a/core/tests/coretests/Android.mk b/core/tests/coretests/Android.mk
deleted file mode 100644
index 3a9d9a3..0000000
--- a/core/tests/coretests/Android.mk
+++ /dev/null
@@ -1,82 +0,0 @@
-ACTUAL_LOCAL_PATH := $(call my-dir)
-
-# this var will hold all the test apk module names later.
-FrameworkCoreTests_all_apks :=
-
-# We have to include the subdir makefiles first
-# so that FrameworkCoreTests_all_apks will be populated correctly.
-include $(call all-makefiles-under,$(ACTUAL_LOCAL_PATH))
-
-LOCAL_PATH := $(ACTUAL_LOCAL_PATH)
-
-include $(CLEAR_VARS)
-
-# We only want this apk build for tests.
-LOCAL_MODULE_TAGS := tests
-
-# Include all test java files.
-LOCAL_SRC_FILES := \
-	$(call all-java-files-under, src) \
-	$(call all-Iaidl-files-under, src) \
-	$(call all-java-files-under, DisabledTestApp/src) \
-	$(call all-java-files-under, EnabledTestApp/src) \
-	$(call all-java-files-under, BinderProxyCountingTestApp/src) \
-	$(call all-java-files-under, BinderProxyCountingTestService/src) \
-	$(call all-Iaidl-files-under, aidl)
-
-LOCAL_AIDL_INCLUDES := $(LOCAL_PATH)/aidl
-
-LOCAL_DX_FLAGS := --core-library
-LOCAL_JACK_FLAGS := --multi-dex native
-LOCAL_AAPT_FLAGS = -0 dat -0 gld -c fa
-LOCAL_STATIC_JAVA_LIBRARIES := \
-    frameworks-base-testutils \
-    core-tests-support \
-    android-common \
-    frameworks-core-util-lib \
-    mockwebserver \
-    guava \
-    android-support-test \
-    mockito-target-minus-junit4 \
-    espresso-core \
-    ub-uiautomator \
-    platform-test-annotations \
-    compatibility-device-util \
-    truth-prebuilt \
-    print-test-util-lib
-
-LOCAL_JAVA_LIBRARIES := \
-    android.test.runner \
-    telephony-common \
-    org.apache.http.legacy \
-    android.test.base \
-    android.test.mock \
-    framework-atb-backward-compatibility \
-
-LOCAL_PACKAGE_NAME := FrameworksCoreTests
-LOCAL_PRIVATE_PLATFORM_APIS := true
-LOCAL_COMPATIBILITY_SUITE := device-tests
-
-LOCAL_CERTIFICATE := platform
-
-# intermediate dir to include all the test apks as raw resource
-FrameworkCoreTests_intermediates := $(call intermediates-dir-for,APPS,$(LOCAL_PACKAGE_NAME))/test_apks/res
-LOCAL_RESOURCE_DIR := $(FrameworkCoreTests_intermediates) $(LOCAL_PATH)/res
-
-# Disable AAPT2 because the hacks below depend on the AAPT rules implementation
-LOCAL_USE_AAPT2 := false
-
-include $(BUILD_PACKAGE)
-# Rules to copy all the test apks to the intermediate raw resource directory
-FrameworkCoreTests_all_apks_res := $(addprefix $(FrameworkCoreTests_intermediates)/raw/, \
-    $(foreach a, $(FrameworkCoreTests_all_apks), $(patsubst FrameworkCoreTests_%,%,$(a))))
-
-$(FrameworkCoreTests_all_apks_res): $(FrameworkCoreTests_intermediates)/raw/%: $(call intermediates-dir-for,APPS,FrameworkCoreTests_%)/package.apk
-	$(call copy-file-to-new-target)
-
-# Use R_file_stamp as dependency because we want the test apks in place before the R.java is generated.
-$(R_file_stamp) : $(FrameworkCoreTests_all_apks_res)
-
-FrameworkCoreTests_all_apks :=
-FrameworkCoreTests_intermediates :=
-FrameworkCoreTests_all_apks_res :=
diff --git a/core/tests/coretests/BinderProxyCountingTestApp/Android.bp b/core/tests/coretests/BinderProxyCountingTestApp/Android.bp
new file mode 100644
index 0000000..6279a48
--- /dev/null
+++ b/core/tests/coretests/BinderProxyCountingTestApp/Android.bp
@@ -0,0 +1,25 @@
+// 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.
+
+android_test_helper_app {
+    name: "BinderProxyCountingTestApp",
+
+    static_libs: ["coretests-aidl"],
+    srcs: ["**/*.java"],
+
+    sdk_version: "current",
+    certificate: "platform",
+
+    test_suites: ["device-tests"],
+}
diff --git a/core/tests/coretests/BinderProxyCountingTestApp/Android.mk b/core/tests/coretests/BinderProxyCountingTestApp/Android.mk
deleted file mode 100644
index 4642694..0000000
--- a/core/tests/coretests/BinderProxyCountingTestApp/Android.mk
+++ /dev/null
@@ -1,29 +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.
-
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_STATIC_JAVA_LIBRARIES := coretests-aidl
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := BinderProxyCountingTestApp
-LOCAL_SDK_VERSION := current
-LOCAL_CERTIFICATE := platform
-
-LOCAL_COMPATIBILITY_SUITE := device-tests
-include $(BUILD_PACKAGE)
-
diff --git a/core/tests/coretests/BinderProxyCountingTestService/Android.bp b/core/tests/coretests/BinderProxyCountingTestService/Android.bp
new file mode 100644
index 0000000..22718cb
--- /dev/null
+++ b/core/tests/coretests/BinderProxyCountingTestService/Android.bp
@@ -0,0 +1,25 @@
+// 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.
+
+android_test_helper_app {
+    name: "BinderProxyCountingTestService",
+
+    static_libs: ["coretests-aidl"],
+    srcs: ["**/*.java"],
+
+    platform_apis: true,
+    certificate: "platform",
+
+    test_suites: ["device-tests"],
+}
diff --git a/core/tests/coretests/BinderProxyCountingTestService/Android.mk b/core/tests/coretests/BinderProxyCountingTestService/Android.mk
deleted file mode 100644
index f852c7a..0000000
--- a/core/tests/coretests/BinderProxyCountingTestService/Android.mk
+++ /dev/null
@@ -1,29 +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.
-
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_STATIC_JAVA_LIBRARIES := coretests-aidl
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := BinderProxyCountingTestService
-LOCAL_PRIVATE_PLATFORM_APIS := true
-LOCAL_CERTIFICATE := platform
-
-LOCAL_COMPATIBILITY_SUITE := device-tests
-include $(BUILD_PACKAGE)
-
diff --git a/core/tests/coretests/BstatsTestApp/Android.bp b/core/tests/coretests/BstatsTestApp/Android.bp
new file mode 100644
index 0000000..424c71a
--- /dev/null
+++ b/core/tests/coretests/BstatsTestApp/Android.bp
@@ -0,0 +1,34 @@
+// 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.
+
+android_test_helper_app {
+    name: "BstatsTestApp",
+
+    test_suites: [
+        "device-tests",
+    ],
+
+    static_libs: ["coretests-aidl"],
+
+    srcs: ["**/*.java"],
+
+    sdk_version: "current",
+    certificate: "platform",
+    dex_preopt: {
+        enabled: false,
+    },
+    optimize: {
+        enabled: false,
+    },
+}
diff --git a/core/tests/coretests/BstatsTestApp/Android.mk b/core/tests/coretests/BstatsTestApp/Android.mk
deleted file mode 100644
index a5872a5..0000000
--- a/core/tests/coretests/BstatsTestApp/Android.mk
+++ /dev/null
@@ -1,34 +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.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_COMPATIBILITY_SUITE := device-tests
-
-LOCAL_STATIC_JAVA_LIBRARIES := coretests-aidl
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := BstatsTestApp
-LOCAL_SDK_VERSION := current
-LOCAL_CERTIFICATE := platform
-LOCAL_DEX_PREOPT := false
-LOCAL_PROGUARD_ENABLED := disabled
-
-LOCAL_COMPATIBILITY_SUITE := device-tests
-include $(BUILD_PACKAGE)
diff --git a/core/tests/coretests/DisabledTestApp/Android.bp b/core/tests/coretests/DisabledTestApp/Android.bp
new file mode 100644
index 0000000..419816e
--- /dev/null
+++ b/core/tests/coretests/DisabledTestApp/Android.bp
@@ -0,0 +1,8 @@
+android_test_helper_app {
+    name: "DisabledTestApp",
+
+    srcs: ["**/*.java"],
+
+    sdk_version: "current",
+    certificate: "platform",
+}
diff --git a/core/tests/coretests/DisabledTestApp/Android.mk b/core/tests/coretests/DisabledTestApp/Android.mk
deleted file mode 100644
index e4304f7..0000000
--- a/core/tests/coretests/DisabledTestApp/Android.mk
+++ /dev/null
@@ -1,13 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := DisabledTestApp
-LOCAL_SDK_VERSION := current
-LOCAL_CERTIFICATE := platform
-
-include $(BUILD_PACKAGE)
-
diff --git a/core/tests/coretests/EnabledTestApp/Android.bp b/core/tests/coretests/EnabledTestApp/Android.bp
new file mode 100644
index 0000000..bc4f4bd
--- /dev/null
+++ b/core/tests/coretests/EnabledTestApp/Android.bp
@@ -0,0 +1,8 @@
+android_test_helper_app {
+    name: "EnabledTestApp",
+
+    srcs: ["**/*.java"],
+
+    sdk_version: "current",
+    certificate: "platform",
+}
diff --git a/core/tests/coretests/EnabledTestApp/Android.mk b/core/tests/coretests/EnabledTestApp/Android.mk
deleted file mode 100644
index cd37f08..0000000
--- a/core/tests/coretests/EnabledTestApp/Android.mk
+++ /dev/null
@@ -1,13 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := EnabledTestApp
-LOCAL_SDK_VERSION := current
-LOCAL_CERTIFICATE := platform
-
-include $(BUILD_PACKAGE)
-
diff --git a/core/tests/coretests/aidl/Android.bp b/core/tests/coretests/aidl/Android.bp
new file mode 100644
index 0000000..6e442db
--- /dev/null
+++ b/core/tests/coretests/aidl/Android.bp
@@ -0,0 +1,19 @@
+// 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.
+
+java_test {
+    name: "coretests-aidl",
+    sdk_version: "current",
+    srcs: ["**/*.aidl"],
+}
diff --git a/core/tests/coretests/aidl/Android.mk b/core/tests/coretests/aidl/Android.mk
deleted file mode 100644
index 86e36b6..0000000
--- a/core/tests/coretests/aidl/Android.mk
+++ /dev/null
@@ -1,22 +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.
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE_TAGS := tests
-LOCAL_SDK_VERSION := current
-LOCAL_SRC_FILES := $(call all-subdir-Iaidl-files)
-LOCAL_MODULE := coretests-aidl
-include $(BUILD_STATIC_JAVA_LIBRARY)
\ No newline at end of file
diff --git a/core/tests/coretests/apks/Android.bp b/core/tests/coretests/apks/Android.bp
new file mode 100644
index 0000000..20c87b2
--- /dev/null
+++ b/core/tests/coretests/apks/Android.bp
@@ -0,0 +1,7 @@
+java_defaults {
+    name: "FrameworksCoreTests_apks_defaults",
+    sdk_version: "current",
+
+    // Every package should have a native library
+    jni_libs: ["libframeworks_coretests_jni"],
+}
diff --git a/core/tests/coretests/apks/Android.mk b/core/tests/coretests/apks/Android.mk
deleted file mode 100644
index 98c0c2a..0000000
--- a/core/tests/coretests/apks/Android.mk
+++ /dev/null
@@ -1,7 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-FrameworkCoreTests_BUILD_PACKAGE := $(LOCAL_PATH)/FrameworkCoreTests_apk.mk
-
-# build sub packages
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/core/tests/coretests/apks/FrameworkCoreTests_apk.mk b/core/tests/coretests/apks/FrameworkCoreTests_apk.mk
deleted file mode 100644
index 8a7d72a5..0000000
--- a/core/tests/coretests/apks/FrameworkCoreTests_apk.mk
+++ /dev/null
@@ -1,16 +0,0 @@
-
-LOCAL_MODULE_TAGS := tests
-
-# Disable dexpreopt.
-LOCAL_DEX_PREOPT := false
-
-# Make sure every package name gets the FrameworkCoreTests_ prefix.
-LOCAL_PACKAGE_NAME := FrameworkCoreTests_$(LOCAL_PACKAGE_NAME)
-LOCAL_SDK_VERSION := current
-
-# Every package should have a native library
-LOCAL_JNI_SHARED_LIBRARIES := libframeworks_coretests_jni
-
-FrameworkCoreTests_all_apks += $(LOCAL_PACKAGE_NAME)
-
-include $(BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install-split-base/Android.bp b/core/tests/coretests/apks/install-split-base/Android.bp
new file mode 100644
index 0000000..ddf75b2
--- /dev/null
+++ b/core/tests/coretests/apks/install-split-base/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_split_base",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install-split-base/Android.mk b/core/tests/coretests/apks/install-split-base/Android.mk
deleted file mode 100644
index 5b60e31..0000000
--- a/core/tests/coretests/apks/install-split-base/Android.mk
+++ /dev/null
@@ -1,10 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_split_base
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
\ No newline at end of file
diff --git a/core/tests/coretests/apks/install-split-feature-a/Android.bp b/core/tests/coretests/apks/install-split-feature-a/Android.bp
new file mode 100644
index 0000000..9ec9893
--- /dev/null
+++ b/core/tests/coretests/apks/install-split-feature-a/Android.bp
@@ -0,0 +1,11 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_split_feature_a",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+
+    aaptflags: [
+        "--custom-package com.google.android.dexapis.splitapp.feature_a",
+        "--package-id 0x80",
+    ],
+}
diff --git a/core/tests/coretests/apks/install-split-feature-a/Android.mk b/core/tests/coretests/apks/install-split-feature-a/Android.mk
deleted file mode 100644
index 0f37d16..0000000
--- a/core/tests/coretests/apks/install-split-feature-a/Android.mk
+++ /dev/null
@@ -1,14 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_split_feature_a
-
-LOCAL_USE_AAPT2 := true
-LOCAL_AAPT_FLAGS += --custom-package com.google.android.dexapis.splitapp.feature_a
-LOCAL_AAPT_FLAGS += --package-id 0x80
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
\ No newline at end of file
diff --git a/core/tests/coretests/apks/install/Android.bp b/core/tests/coretests/apks/install/Android.bp
new file mode 100644
index 0000000..e783fe2
--- /dev/null
+++ b/core/tests/coretests/apks/install/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install/Android.mk b/core/tests/coretests/apks/install/Android.mk
deleted file mode 100644
index b38dc20..0000000
--- a/core/tests/coretests/apks/install/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_bad_dex/Android.bp b/core/tests/coretests/apks/install_bad_dex/Android.bp
new file mode 100644
index 0000000..d156793
--- /dev/null
+++ b/core/tests/coretests/apks/install_bad_dex/Android.bp
@@ -0,0 +1,23 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_bad_dex_",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["src/**/*.java"],
+}
+
+// Inject bad classes.dex file.
+java_genrule {
+    name: "FrameworksCoreTests_install_bad_dex",
+    tools: [
+        "soong_zip",
+        "merge_zips",
+    ],
+    srcs: [
+        ":FrameworksCoreTests_install_bad_dex_",
+        "classes.dex",
+    ],
+    out: ["FrameworksCoreTests_install_bad_dex.apk"],
+    cmd: "$(location soong_zip) -o $(genDir)/classes.dex.zip -j -f $(location classes.dex) && " +
+        "$(location merge_zips) -ignore-duplicates $(out) $(genDir)/classes.dex.zip " +
+        "$(location :FrameworksCoreTests_install_bad_dex_)",
+}
diff --git a/core/tests/coretests/apks/install_bad_dex/Android.mk b/core/tests/coretests/apks/install_bad_dex/Android.mk
deleted file mode 100644
index 05983aa..0000000
--- a/core/tests/coretests/apks/install_bad_dex/Android.mk
+++ /dev/null
@@ -1,11 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_bad_dex
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-# Override target specific variable PRIVATE_DEX_FILE to inject bad classes.dex file.
-$(LOCAL_BUILT_MODULE): PRIVATE_DEX_FILE := $(LOCAL_PATH)/classes.dex
diff --git a/core/tests/coretests/apks/install_complete_package_info/Android.bp b/core/tests/coretests/apks/install_complete_package_info/Android.bp
new file mode 100644
index 0000000..123558bd
--- /dev/null
+++ b/core/tests/coretests/apks/install_complete_package_info/Android.bp
@@ -0,0 +1,7 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_complete_package_info",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
+
diff --git a/core/tests/coretests/apks/install_complete_package_info/Android.mk b/core/tests/coretests/apks/install_complete_package_info/Android.mk
deleted file mode 100644
index 19bf356..0000000
--- a/core/tests/coretests/apks/install_complete_package_info/Android.mk
+++ /dev/null
@@ -1,13 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_complete_package_info
-#LOCAL_MANIFEST_FILE := api_test/AndroidManifest.xml
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-#include $(BUILD_PACKAGE)
-
diff --git a/core/tests/coretests/apks/install_decl_perm/Android.bp b/core/tests/coretests/apks/install_decl_perm/Android.bp
new file mode 100644
index 0000000..868e8b5
--- /dev/null
+++ b/core/tests/coretests/apks/install_decl_perm/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_decl_perm",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_decl_perm/Android.mk b/core/tests/coretests/apks/install_decl_perm/Android.mk
deleted file mode 100644
index 86370c8..0000000
--- a/core/tests/coretests/apks/install_decl_perm/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_decl_perm
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_jni_lib/Android.bp b/core/tests/coretests/apks/install_jni_lib/Android.bp
index c1a6bd0..f20f599 100644
--- a/core/tests/coretests/apks/install_jni_lib/Android.bp
+++ b/core/tests/coretests/apks/install_jni_lib/Android.bp
@@ -14,6 +14,7 @@
 
 cc_test_library {
     name: "libframeworks_coretests_jni",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
 
     srcs: ["com_android_frameworks_coretests_JNITest.cpp"],
 
diff --git a/core/tests/coretests/apks/install_jni_lib_open_from_apk/Android.bp b/core/tests/coretests/apks/install_jni_lib_open_from_apk/Android.bp
new file mode 100644
index 0000000..602b704
--- /dev/null
+++ b/core/tests/coretests/apks/install_jni_lib_open_from_apk/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_jni_lib_open_from_apk",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_jni_lib_open_from_apk/Android.mk b/core/tests/coretests/apks/install_jni_lib_open_from_apk/Android.mk
deleted file mode 100644
index 6b3b55e..0000000
--- a/core/tests/coretests/apks/install_jni_lib_open_from_apk/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_jni_lib_open_from_apk
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_loc_auto/Android.bp b/core/tests/coretests/apks/install_loc_auto/Android.bp
new file mode 100644
index 0000000..6393915
--- /dev/null
+++ b/core/tests/coretests/apks/install_loc_auto/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_loc_auto",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_loc_auto/Android.mk b/core/tests/coretests/apks/install_loc_auto/Android.mk
deleted file mode 100644
index 6435f36..0000000
--- a/core/tests/coretests/apks/install_loc_auto/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_loc_auto
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_loc_internal/Android.bp b/core/tests/coretests/apks/install_loc_internal/Android.bp
new file mode 100644
index 0000000..770aaa5
--- /dev/null
+++ b/core/tests/coretests/apks/install_loc_internal/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_loc_internal",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_loc_internal/Android.mk b/core/tests/coretests/apks/install_loc_internal/Android.mk
deleted file mode 100644
index 8cc8b8e..0000000
--- a/core/tests/coretests/apks/install_loc_internal/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_loc_internal
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_loc_sdcard/Android.bp b/core/tests/coretests/apks/install_loc_sdcard/Android.bp
new file mode 100644
index 0000000..1779401
--- /dev/null
+++ b/core/tests/coretests/apks/install_loc_sdcard/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_loc_sdcard",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_loc_sdcard/Android.mk b/core/tests/coretests/apks/install_loc_sdcard/Android.mk
deleted file mode 100644
index e1411c2..0000000
--- a/core/tests/coretests/apks/install_loc_sdcard/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_loc_sdcard
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_loc_unspecified/Android.bp b/core/tests/coretests/apks/install_loc_unspecified/Android.bp
new file mode 100644
index 0000000..21c0f82
--- /dev/null
+++ b/core/tests/coretests/apks/install_loc_unspecified/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_loc_unspecified",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_loc_unspecified/Android.mk b/core/tests/coretests/apks/install_loc_unspecified/Android.mk
deleted file mode 100644
index 0741d04..0000000
--- a/core/tests/coretests/apks/install_loc_unspecified/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_loc_unspecified
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_multi_package/Android.bp b/core/tests/coretests/apks/install_multi_package/Android.bp
new file mode 100644
index 0000000..249242e
--- /dev/null
+++ b/core/tests/coretests/apks/install_multi_package/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_multi_package",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_multi_package/Android.mk b/core/tests/coretests/apks/install_multi_package/Android.mk
deleted file mode 100644
index 3f163de..0000000
--- a/core/tests/coretests/apks/install_multi_package/Android.mk
+++ /dev/null
@@ -1,14 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_multi_package
-
-LOCAL_USE_AAPT2 := true
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-#include $(BUILD_PACKAGE)
-
diff --git a/core/tests/coretests/apks/install_use_perm_good/Android.bp b/core/tests/coretests/apks/install_use_perm_good/Android.bp
new file mode 100644
index 0000000..bb41ebb
--- /dev/null
+++ b/core/tests/coretests/apks/install_use_perm_good/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_use_perm_good",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_use_perm_good/Android.mk b/core/tests/coretests/apks/install_use_perm_good/Android.mk
deleted file mode 100644
index e2661a1..0000000
--- a/core/tests/coretests/apks/install_use_perm_good/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_use_perm_good
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_uses_feature/Android.bp b/core/tests/coretests/apks/install_uses_feature/Android.bp
new file mode 100644
index 0000000..0ec747b
--- /dev/null
+++ b/core/tests/coretests/apks/install_uses_feature/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_uses_feature",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_uses_feature/Android.mk b/core/tests/coretests/apks/install_uses_feature/Android.mk
deleted file mode 100644
index b60d734..0000000
--- a/core/tests/coretests/apks/install_uses_feature/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_uses_feature
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_verifier_bad/Android.bp b/core/tests/coretests/apks/install_verifier_bad/Android.bp
new file mode 100644
index 0000000..1265739
--- /dev/null
+++ b/core/tests/coretests/apks/install_verifier_bad/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_verifier_bad",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_verifier_bad/Android.mk b/core/tests/coretests/apks/install_verifier_bad/Android.mk
deleted file mode 100644
index 745b4d3..0000000
--- a/core/tests/coretests/apks/install_verifier_bad/Android.mk
+++ /dev/null
@@ -1,10 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_verifier_bad
-
-LOCAL_USE_AAPT2 := true
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/install_verifier_good/Android.bp b/core/tests/coretests/apks/install_verifier_good/Android.bp
new file mode 100644
index 0000000..4911ffb
--- /dev/null
+++ b/core/tests/coretests/apks/install_verifier_good/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_install_verifier_good",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/install_verifier_good/Android.mk b/core/tests/coretests/apks/install_verifier_good/Android.mk
deleted file mode 100644
index 150fd8d..0000000
--- a/core/tests/coretests/apks/install_verifier_good/Android.mk
+++ /dev/null
@@ -1,10 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := install_verifier_good
-
-LOCAL_USE_AAPT2 := true
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/keyset/Android.bp b/core/tests/coretests/apks/keyset/Android.bp
new file mode 100644
index 0000000..e252b08
--- /dev/null
+++ b/core/tests/coretests/apks/keyset/Android.bp
@@ -0,0 +1,120 @@
+//apks signed by keyset_A
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sa_unone",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    manifest: "uNone/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sa_ua",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    manifest: "uA/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sa_ub",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    manifest: "uB/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sa_uab",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    manifest: "uAB/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sa_ua_ub",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    manifest: "uAuB/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_permdef_sa_unone",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    manifest: "permDef/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_permuse_sa_ua_ub",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    manifest: "permUse/AndroidManifest.xml",
+}
+
+//apks signed by keyset_B
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sb_ua",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_B_cert",
+    manifest: "uA/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sb_ub",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_B_cert",
+    manifest: "uB/AndroidManifest.xml",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_permuse_sb_ua_ub",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_B_cert",
+    manifest: "permUse/AndroidManifest.xml",
+}
+
+//apks signed by keyset_A and keyset_B
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sab_ua",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    additional_certificates: [":FrameworksCoreTests_keyset_B_cert"],
+    manifest: "uA/AndroidManifest.xml",
+}
+
+//apks signed by keyset_A and unit_test
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_sau_ub",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: ":FrameworksCoreTests_keyset_A_cert",
+    additional_certificates: [":FrameworksCoreTests_keyset_B_cert"],
+    manifest: "uB/AndroidManifest.xml",
+}
+
+//apks signed by platform only
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_splat_api",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: "platform",
+    manifest: "api_test/AndroidManifest.xml",
+}
+
+//apks signed by platform and keyset_A
+android_test_helper_app {
+    name: "FrameworksCoreTests_keyset_splata_api",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    certificate: "platform",
+    additional_certificates: [":FrameworksCoreTests_keyset_A_cert"],
+    manifest: "api_test/AndroidManifest.xml",
+}
diff --git a/core/tests/coretests/apks/keyset/Android.mk b/core/tests/coretests/apks/keyset/Android.mk
deleted file mode 100644
index 306dc90..0000000
--- a/core/tests/coretests/apks/keyset/Android.mk
+++ /dev/null
@@ -1,108 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-#apks signed by keyset_A
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sa_unone
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := uNone/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sa_ua
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := uA/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sa_ub
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := uB/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sa_uab
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := uAB/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sa_ua_ub
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := uAuB/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_permdef_sa_unone
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := permDef/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_permuse_sa_ua_ub
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := permUse/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-#apks signed by keyset_B
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sb_ua
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_B
-LOCAL_MANIFEST_FILE := uA/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sb_ub
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_B
-LOCAL_MANIFEST_FILE := uB/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_permuse_sb_ua_ub
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_B
-LOCAL_MANIFEST_FILE := permUse/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-#apks signed by keyset_A and keyset_B
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sab_ua
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_ADDITIONAL_CERTIFICATES := $(LOCAL_PATH)/../../certs/keyset_B
-LOCAL_MANIFEST_FILE := uA/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-#apks signed by keyset_A and unit_test
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_sau_ub
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_ADDITIONAL_CERTIFICATES := $(LOCAL_PATH)/../../certs/keyset_B
-LOCAL_MANIFEST_FILE := uB/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-#apks signed by platform only
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_splat_api
-LOCAL_CERTIFICATE := platform
-LOCAL_MANIFEST_FILE := api_test/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-#apks signed by platform and keyset_A
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := keyset_splata_api
-LOCAL_CERTIFICATE := platform
-LOCAL_ADDITIONAL_CERTIFICATES := $(LOCAL_PATH)/../../certs/keyset_A
-LOCAL_MANIFEST_FILE := api_test/AndroidManifest.xml
-include $(FrameworkCoreTests_BUILD_PACKAGE)
\ No newline at end of file
diff --git a/core/tests/coretests/apks/locales/Android.bp b/core/tests/coretests/apks/locales/Android.bp
new file mode 100644
index 0000000..4a730ef
--- /dev/null
+++ b/core/tests/coretests/apks/locales/Android.bp
@@ -0,0 +1,6 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_locales",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+
+    srcs: ["**/*.java"],
+}
diff --git a/core/tests/coretests/apks/locales/Android.mk b/core/tests/coretests/apks/locales/Android.mk
deleted file mode 100644
index 9cb13dd..0000000
--- a/core/tests/coretests/apks/locales/Android.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_PACKAGE_NAME := locales
-
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/version/Android.bp b/core/tests/coretests/apks/version/Android.bp
new file mode 100644
index 0000000..371ccfc
--- /dev/null
+++ b/core/tests/coretests/apks/version/Android.bp
@@ -0,0 +1,54 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_version_1",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    aaptflags: [
+        "--version-code 1",
+        "--version-name 1.0",
+    ],
+    certificate: ":FrameworksCoreTests_unit_test_cert",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_version_2",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    aaptflags: [
+        "--version-code 2",
+        "--version-name 2.0",
+    ],
+    certificate: ":FrameworksCoreTests_unit_test_cert",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_version_3",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    aaptflags: [
+        "--version-code 3",
+        "--version-name 3.0",
+    ],
+    certificate: ":FrameworksCoreTests_unit_test_cert",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_version_1_diff",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    aaptflags: [
+        "--version-code 1",
+        "--version-name 1.0",
+    ],
+    certificate: ":FrameworksCoreTests_unit_test_cert",
+}
+
+android_test_helper_app {
+    name: "FrameworksCoreTests_version_2_diff",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    aaptflags: [
+        "--version-code 2",
+        "--version-name 2.0",
+    ],
+    certificate: ":FrameworksCoreTests_unit_test_cert",
+}
diff --git a/core/tests/coretests/apks/version/Android.mk b/core/tests/coretests/apks/version/Android.mk
deleted file mode 100644
index 3635a58..0000000
--- a/core/tests/coretests/apks/version/Android.mk
+++ /dev/null
@@ -1,36 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := version_1
-LOCAL_AAPT_FLAGS := --version-code 1 --version-name 1.0
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/unit_test
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := version_2
-LOCAL_AAPT_FLAGS := --version-code 2 --version-name 2.0
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/unit_test
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := version_3
-LOCAL_AAPT_FLAGS := --version-code 3 --version-name 3.0
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/unit_test
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := version_1_diff
-LOCAL_AAPT_FLAGS := --version-code 1 --version-name 1.0
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/unit_test_diff
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := version_2_diff
-LOCAL_AAPT_FLAGS := --version-code 2 --version-name 2.0
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/unit_test_diff
-include $(FrameworkCoreTests_BUILD_PACKAGE)
diff --git a/core/tests/coretests/apks/version_nosys/Android.bp b/core/tests/coretests/apks/version_nosys/Android.bp
new file mode 100644
index 0000000..5756678
--- /dev/null
+++ b/core/tests/coretests/apks/version_nosys/Android.bp
@@ -0,0 +1,10 @@
+android_test_helper_app {
+    name: "FrameworksCoreTests_version_1_nosys",
+    defaults: ["FrameworksCoreTests_apks_defaults"],
+    srcs: ["**/*.java"],
+    aaptflags: [
+        "--version-code 1",
+        "--version-name 1.0",
+    ],
+    certificate: ":FrameworksCoreTests_unit_test_cert",
+}
diff --git a/core/tests/coretests/apks/version_nosys/Android.mk b/core/tests/coretests/apks/version_nosys/Android.mk
deleted file mode 100644
index bbc8e12..0000000
--- a/core/tests/coretests/apks/version_nosys/Android.mk
+++ /dev/null
@@ -1,9 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_PACKAGE_NAME := version_1_nosys
-LOCAL_AAPT_FLAGS := --version-code 1 --version-name 1.0
-LOCAL_CERTIFICATE := $(LOCAL_PATH)/../../certs/unit_test
-include $(FrameworkCoreTests_BUILD_PACKAGE)
-
diff --git a/core/tests/coretests/certs/Android.bp b/core/tests/coretests/certs/Android.bp
new file mode 100644
index 0000000..bd5c829
--- /dev/null
+++ b/core/tests/coretests/certs/Android.bp
@@ -0,0 +1,14 @@
+android_app_certificate {
+    name: "FrameworksCoreTests_keyset_A_cert",
+    certificate: "keyset_A",
+}
+
+android_app_certificate {
+    name: "FrameworksCoreTests_keyset_B_cert",
+    certificate: "keyset_B",
+}
+
+android_app_certificate {
+    name: "FrameworksCoreTests_unit_test_cert",
+    certificate: "unit_test",
+}
diff --git a/core/tests/coretests/src/android/app/timezone/RulesStateTest.java b/core/tests/coretests/src/android/app/timezone/RulesStateTest.java
index dd46240..e22cb89 100644
--- a/core/tests/coretests/src/android/app/timezone/RulesStateTest.java
+++ b/core/tests/coretests/src/android/app/timezone/RulesStateTest.java
@@ -16,8 +16,6 @@
 
 package android.app.timezone;
 
-import static junit.framework.Assert.fail;
-
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
@@ -47,11 +45,11 @@
                 RulesState.DISTRO_STATUS_INSTALLED, rulesVersion("2016b", 2));
         assertEqualsContract(one, two);
 
-        RulesState differentSystemRules = new RulesState(
+        RulesState differentBaseRules = new RulesState(
                 "2016b", formatVersion(1, 2), false /* operationInProgress */,
                 RulesState.STAGED_OPERATION_INSTALL, rulesVersion("2016a", 3),
                 RulesState.DISTRO_STATUS_INSTALLED, rulesVersion("2016b", 2));
-        assertFalse(one.equals(differentSystemRules));
+        assertFalse(one.equals(differentBaseRules));
 
         RulesState differentFormatVersion = new RulesState(
                 "2016a", formatVersion(1, 1), false /* operationInProgress */,
@@ -122,14 +120,14 @@
     }
 
     @Test
-    public void isSystemVersionNewerThan() {
+    public void isBaseVersionNewerThan() {
         RulesState rulesState = new RulesState(
                 "2016b", formatVersion(1, 1), false /* operationInProgress */,
                 RulesState.STAGED_OPERATION_NONE, null /* stagedDistroRulesVersion */,
                 RulesState.DISTRO_STATUS_INSTALLED, rulesVersion("2016b", 3));
-        assertTrue(rulesState.isSystemVersionNewerThan(rulesVersion("2016a", 1)));
-        assertFalse(rulesState.isSystemVersionNewerThan(rulesVersion("2016b", 1)));
-        assertFalse(rulesState.isSystemVersionNewerThan(rulesVersion("2016c", 1)));
+        assertTrue(rulesState.isBaseVersionNewerThan(rulesVersion("2016a", 1)));
+        assertFalse(rulesState.isBaseVersionNewerThan(rulesVersion("2016b", 1)));
+        assertFalse(rulesState.isBaseVersionNewerThan(rulesVersion("2016c", 1)));
     }
 
     private static void assertEqualsContract(RulesState one, RulesState two) {
diff --git a/core/tests/utillib/Android.bp b/core/tests/utillib/Android.bp
new file mode 100644
index 0000000..1f742c2
--- /dev/null
+++ b/core/tests/utillib/Android.bp
@@ -0,0 +1,22 @@
+// Copyright (C) 2010 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_library {
+    name: "frameworks-core-util-lib",
+
+    srcs: ["**/*.java"],
+
+    static_libs: ["junit"],
+    libs: ["android.test.base"],
+}
diff --git a/core/tests/utillib/Android.mk b/core/tests/utillib/Android.mk
deleted file mode 100644
index be1ab1f..0000000
--- a/core/tests/utillib/Android.mk
+++ /dev/null
@@ -1,29 +0,0 @@
-# Copyright (C) 2010 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_MODULE := frameworks-core-util-lib
-LOCAL_STATIC_JAVA_LIBRARIES := junit
-LOCAL_JAVA_LIBRARIES := android.test.base
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-# Build the test APKs using their own makefiles
-include $(call all-makefiles-under,$(LOCAL_PATH))
-
diff --git a/graphics/java/android/graphics/Bitmap.java b/graphics/java/android/graphics/Bitmap.java
index d6131cf..507f767a 100644
--- a/graphics/java/android/graphics/Bitmap.java
+++ b/graphics/java/android/graphics/Bitmap.java
@@ -814,7 +814,7 @@
      * @return A bitmap that represents the specified subset of source
      * @throws IllegalArgumentException if the x, y, width, height values are
      *         outside of the dimensions of the source bitmap, or width is <= 0,
-     *         or height is <= 0
+     *         or height is <= 0, or if the source bitmap has already been recycled
      */
     public static Bitmap createBitmap(@NonNull Bitmap source, int x, int y, int width, int height,
             @Nullable Matrix m, boolean filter) {
@@ -827,6 +827,9 @@
         if (y + height > source.getHeight()) {
             throw new IllegalArgumentException("y + height must be <= bitmap.height()");
         }
+        if (source.isRecycled()) {
+            throw new IllegalArgumentException("cannot use a recycled source in createBitmap");
+        }
 
         // check if we can just return our argument unchanged
         if (!source.isMutable() && x == 0 && y == 0 && width == source.getWidth() &&
diff --git a/packages/NetworkStack/src/android/net/metrics/DataStallDetectionStats.java b/packages/NetworkStack/src/android/net/metrics/DataStallDetectionStats.java
index 6ea1e3d..225dc0f 100644
--- a/packages/NetworkStack/src/android/net/metrics/DataStallDetectionStats.java
+++ b/packages/NetworkStack/src/android/net/metrics/DataStallDetectionStats.java
@@ -30,7 +30,9 @@
 import com.google.protobuf.nano.MessageNano;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Class to record the stats of detection level information for data stall.
@@ -96,6 +98,22 @@
         return sb.toString();
     }
 
+    @Override
+    public boolean equals(@Nullable final Object o) {
+        if (!(o instanceof DataStallDetectionStats)) return false;
+        final DataStallDetectionStats other = (DataStallDetectionStats) o;
+        return (mNetworkType == other.mNetworkType)
+            && (mEvaluationType == other.mEvaluationType)
+            && Arrays.equals(mWifiInfo, other.mWifiInfo)
+            && Arrays.equals(mCellularInfo, other.mCellularInfo)
+            && Arrays.equals(mDns, other.mDns);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(mNetworkType, mEvaluationType, mWifiInfo, mCellularInfo, mDns);
+    }
+
     /**
      * Utility to create an instance of {@Link DataStallDetectionStats}
      *
@@ -163,16 +181,17 @@
         }
 
         private static int getWifiBand(@Nullable final WifiInfo info) {
-            if (info != null) {
-                int freq = info.getFrequency();
-                // Refer to ScanResult.is5GHz() and ScanResult.is24GHz().
-                if (freq > 4900 && freq < 5900) {
-                    return DataStallEventProto.AP_BAND_5GHZ;
-                } else if (freq > 2400 && freq < 2500) {
-                    return DataStallEventProto.AP_BAND_2GHZ;
-                }
+            if (info == null) return DataStallEventProto.AP_BAND_UNKNOWN;
+
+            int freq = info.getFrequency();
+            // Refer to ScanResult.is5GHz() and ScanResult.is24GHz().
+            if (freq > 4900 && freq < 5900) {
+                return DataStallEventProto.AP_BAND_5GHZ;
+            } else if (freq > 2400 && freq < 2500) {
+                return DataStallEventProto.AP_BAND_2GHZ;
+            } else {
+                return DataStallEventProto.AP_BAND_UNKNOWN;
             }
-            return DataStallEventProto.AP_BAND_UNKNOWN;
         }
 
         /**
diff --git a/packages/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java b/packages/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java
index 3c129ce..e82a5d7 100644
--- a/packages/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java
+++ b/packages/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java
@@ -729,7 +729,8 @@
         return stats.build();
     }
 
-    private void addDnsEvents(@NonNull final DataStallDetectionStats.Builder stats) {
+    @VisibleForTesting
+    protected void addDnsEvents(@NonNull final DataStallDetectionStats.Builder stats) {
         final int size = mDnsStallDetector.mResultIndices.size();
         for (int i = 1; i <= DEFAULT_DNS_LOG_SIZE && i <= size; i++) {
             final int index = mDnsStallDetector.mResultIndices.indexOf(size - i);
diff --git a/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java b/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java
index beb975d..ddb7030 100644
--- a/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java
+++ b/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java
@@ -30,7 +30,6 @@
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.anyObject;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.doThrow;
@@ -40,6 +39,7 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import android.annotation.NonNull;
 import android.content.Context;
 import android.net.ConnectivityManager;
 import android.net.INetworkMonitorCallbacks;
@@ -49,9 +49,11 @@
 import android.net.NetworkCapabilities;
 import android.net.NetworkInfo;
 import android.net.captiveportal.CaptivePortalProbeResult;
+import android.net.metrics.DataStallDetectionStats;
 import android.net.metrics.DataStallStatsUtils;
 import android.net.metrics.IpConnectivityLog;
 import android.net.util.SharedLog;
+import android.net.wifi.WifiInfo;
 import android.net.wifi.WifiManager;
 import android.os.Bundle;
 import android.os.ConditionVariable;
@@ -60,6 +62,7 @@
 import android.provider.Settings;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
+import android.telephony.CellSignalStrength;
 import android.telephony.TelephonyManager;
 import android.util.ArrayMap;
 
@@ -101,6 +104,7 @@
     private @Mock INetworkMonitorCallbacks mCallbacks;
     private @Spy Network mNetwork = new Network(TEST_NETID);
     private @Mock DataStallStatsUtils mDataStallStatsUtils;
+    private @Mock WifiInfo mWifiInfo;
 
     private static final int TEST_NETID = 4242;
 
@@ -108,10 +112,12 @@
     private static final String TEST_HTTPS_URL = "https://www.google.com/gen_204";
     private static final String TEST_FALLBACK_URL = "http://fallback.google.com/gen_204";
     private static final String TEST_OTHER_FALLBACK_URL = "http://otherfallback.google.com/gen_204";
+    private static final String TEST_MCCMNC = "123456";
 
     private static final int DATA_STALL_EVALUATION_TYPE_DNS = 1;
     private static final int RETURN_CODE_DNS_SUCCESS = 0;
     private static final int RETURN_CODE_DNS_TIMEOUT = 255;
+    private static final int DEFAULT_DNS_TIMEOUT_THRESHOLD = 5;
 
     private static final int HANDLER_TIMEOUT_MS = 1000;
 
@@ -202,6 +208,11 @@
         protected void setLastProbeTime(long time) {
             mProbeTime = time;
         }
+
+        @Override
+        protected void addDnsEvents(@NonNull final DataStallDetectionStats.Builder stats) {
+            generateTimeoutDnsEvent(stats, DEFAULT_DNS_TIMEOUT_THRESHOLD);
+        }
     }
 
     private WrappedNetworkMonitor makeMeteredWrappedNetworkMonitor() {
@@ -387,7 +398,7 @@
     public void testIsDataStall_EvaluationDnsOnNotMeteredNetwork() {
         WrappedNetworkMonitor wrappedMonitor = makeNotMeteredWrappedNetworkMonitor();
         wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 100);
-        makeDnsTimeoutEvent(wrappedMonitor, 5);
+        makeDnsTimeoutEvent(wrappedMonitor, DEFAULT_DNS_TIMEOUT_THRESHOLD);
         assertTrue(wrappedMonitor.isDataStall());
     }
 
@@ -398,7 +409,7 @@
         assertFalse(wrappedMonitor.isDataStall());
 
         wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000);
-        makeDnsTimeoutEvent(wrappedMonitor, 5);
+        makeDnsTimeoutEvent(wrappedMonitor, DEFAULT_DNS_TIMEOUT_THRESHOLD);
         assertTrue(wrappedMonitor.isDataStall());
     }
 
@@ -432,7 +443,7 @@
         // Test dns events happened in valid dns time threshold.
         WrappedNetworkMonitor wrappedMonitor = makeMeteredWrappedNetworkMonitor();
         wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 100);
-        makeDnsTimeoutEvent(wrappedMonitor, 5);
+        makeDnsTimeoutEvent(wrappedMonitor, DEFAULT_DNS_TIMEOUT_THRESHOLD);
         assertFalse(wrappedMonitor.isDataStall());
         wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000);
         assertTrue(wrappedMonitor.isDataStall());
@@ -441,7 +452,7 @@
         setValidDataStallDnsTimeThreshold(0);
         wrappedMonitor = makeMeteredWrappedNetworkMonitor();
         wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 100);
-        makeDnsTimeoutEvent(wrappedMonitor, 5);
+        makeDnsTimeoutEvent(wrappedMonitor, DEFAULT_DNS_TIMEOUT_THRESHOLD);
         assertFalse(wrappedMonitor.isDataStall());
         wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000);
         assertFalse(wrappedMonitor.isDataStall());
@@ -514,7 +525,7 @@
         wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000);
         makeDnsTimeoutEvent(wrappedMonitor, 5);
         assertTrue(wrappedMonitor.isDataStall());
-        verify(mDataStallStatsUtils, times(1)).write(eq(anyObject()), eq(anyObject()));
+        verify(mDataStallStatsUtils, times(1)).write(any(), any());
     }
 
     @Test
@@ -523,8 +534,44 @@
         wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000);
         makeDnsTimeoutEvent(wrappedMonitor, 3);
         assertFalse(wrappedMonitor.isDataStall());
-        verify(mDataStallStatsUtils, times(0)).write(eq(anyObject()), eq(anyObject()));
+        verify(mDataStallStatsUtils, never()).write(any(), any());
     }
+
+    @Test
+    public void testCollectDataStallMetrics() {
+        WrappedNetworkMonitor wrappedMonitor = makeNotMeteredWrappedNetworkMonitor();
+
+        when(mTelephony.getDataNetworkType()).thenReturn(TelephonyManager.NETWORK_TYPE_LTE);
+        when(mTelephony.getNetworkOperator()).thenReturn(TEST_MCCMNC);
+        when(mTelephony.getSimOperator()).thenReturn(TEST_MCCMNC);
+
+        DataStallDetectionStats.Builder stats =
+                new DataStallDetectionStats.Builder()
+                .setEvaluationType(DATA_STALL_EVALUATION_TYPE_DNS)
+                .setNetworkType(NetworkCapabilities.TRANSPORT_CELLULAR)
+                .setCellData(TelephonyManager.NETWORK_TYPE_LTE /* radioType */,
+                        true /* roaming */,
+                        TEST_MCCMNC /* networkMccmnc */,
+                        TEST_MCCMNC /* simMccmnc */,
+                        CellSignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN /* signalStrength */);
+        generateTimeoutDnsEvent(stats, DEFAULT_DNS_TIMEOUT_THRESHOLD);
+
+        assertEquals(wrappedMonitor.buildDataStallDetectionStats(
+                 NetworkCapabilities.TRANSPORT_CELLULAR), stats.build());
+
+        when(mWifi.getConnectionInfo()).thenReturn(mWifiInfo);
+
+        stats = new DataStallDetectionStats.Builder()
+                .setEvaluationType(DATA_STALL_EVALUATION_TYPE_DNS)
+                .setNetworkType(NetworkCapabilities.TRANSPORT_WIFI)
+                .setWiFiData(mWifiInfo);
+        generateTimeoutDnsEvent(stats, DEFAULT_DNS_TIMEOUT_THRESHOLD);
+
+        assertEquals(
+                wrappedMonitor.buildDataStallDetectionStats(NetworkCapabilities.TRANSPORT_WIFI),
+                stats.build());
+    }
+
     private void makeDnsTimeoutEvent(WrappedNetworkMonitor wrappedMonitor, int count) {
         for (int i = 0; i < count; i++) {
             wrappedMonitor.getDnsStallDetector().accumulateConsecutiveDnsTimeoutCount(
@@ -614,5 +661,11 @@
     private void setStatus(HttpURLConnection connection, int status) throws IOException {
         doReturn(status).when(connection).getResponseCode();
     }
+
+    private void generateTimeoutDnsEvent(DataStallDetectionStats.Builder stats, int num) {
+        for (int i = 0; i < num; i++) {
+            stats.addDnsEvent(RETURN_CODE_DNS_TIMEOUT, 123456789 /* timeMs */);
+        }
+    }
 }
 
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index b277666..40c8b01 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -136,6 +136,7 @@
     <uses-permission android:name="android.permission.SET_TIME_ZONE" />
     <uses-permission android:name="android.permission.DISABLE_HIDDEN_API_CHECKS" />
     <uses-permission android:name="android.permission.MANAGE_ROLE_HOLDERS" />
+    <uses-permission android:name="android.permission.OBSERVE_ROLE_HOLDERS" />
     <!-- Permission needed to rename bugreport notifications (so they're not shown as Shell) -->
     <uses-permission android:name="android.permission.SUBSTITUTE_NOTIFICATION_APP_NAME" />
     <!-- Permission needed to hold a wakelock in dumpstate.cpp (drop_root_user()) -->
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index 1035efb..446d186 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -71,6 +71,8 @@
 import android.net.INetworkPolicyListener;
 import android.net.INetworkPolicyManager;
 import android.net.INetworkStatsService;
+import android.net.InetAddresses;
+import android.net.IpPrefix;
 import android.net.LinkProperties;
 import android.net.LinkProperties.CompareResult;
 import android.net.MatchAllNetworkSpecifier;
@@ -1740,6 +1742,12 @@
                 }
             }
         }
+
+        @Override
+        public void onNat64PrefixEvent(int netId, boolean added,
+                                       String prefixString, int prefixLength) {
+            mHandler.post(() -> handleNat64PrefixEvent(netId, added, prefixString, prefixLength));
+        }
     };
 
     @VisibleForTesting
@@ -2767,6 +2775,29 @@
         handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
     }
 
+    private void handleNat64PrefixEvent(int netId, boolean added, String prefixString,
+            int prefixLength) {
+        NetworkAgentInfo nai = mNetworkForNetId.get(netId);
+        if (nai == null) return;
+
+        log(String.format("NAT64 prefix %s on netId %d: %s/%d",
+                          (added ? "added" : "removed"), netId, prefixString, prefixLength));
+
+        IpPrefix prefix = null;
+        if (added) {
+            try {
+                prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixString),
+                        prefixLength);
+            } catch (IllegalArgumentException e) {
+                loge("Invalid NAT64 prefix " + prefixString + "/" + prefixLength);
+                return;
+            }
+        }
+
+        nai.clatd.setNat64Prefix(prefix);
+        handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
+    }
+
     private void updateLingerState(NetworkAgentInfo nai, long now) {
         // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
         // 2. If the network was lingering and there are now requests, unlinger it.
@@ -2882,7 +2913,7 @@
             e.rethrowFromSystemServer();
         }
         mNetworkAgentInfos.remove(nai.messenger);
-        nai.maybeStopClat();
+        nai.clatd.update();
         synchronized (mNetworkForNetId) {
             // Remove the NetworkAgent, but don't mark the netId as
             // available until we've told netd to delete it below.
@@ -5190,11 +5221,10 @@
             LinkProperties oldLp) {
         int netId = networkAgent.network.netId;
 
-        // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
-        // we do anything else, make sure its LinkProperties are accurate.
-        if (networkAgent.clatd != null) {
-            networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
-        }
+        // The NetworkAgentInfo does not know whether clatd is running on its network or not, or
+        // whether there is a NAT64 prefix. Before we do anything else, make sure its LinkProperties
+        // are accurate.
+        networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
 
         updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
         updateMtu(newLp, oldLp);
@@ -5224,8 +5254,8 @@
             synchronized (networkAgent) {
                 networkAgent.linkProperties = newLp;
             }
-            // Start or stop clat accordingly to network state.
-            networkAgent.updateClat(mNMS);
+            // Start or stop DNS64 detection and 464xlat according to network state.
+            networkAgent.clatd.update();
             notifyIfacesChangedForNetworkStats();
             if (networkAgent.everConnected) {
                 try {
diff --git a/services/core/java/com/android/server/TelephonyRegistry.java b/services/core/java/com/android/server/TelephonyRegistry.java
index 3b5c9f5..b4d45d4 100644
--- a/services/core/java/com/android/server/TelephonyRegistry.java
+++ b/services/core/java/com/android/server/TelephonyRegistry.java
@@ -177,8 +177,6 @@
 
     private ServiceState[] mServiceState;
 
-    private int[] mNetworkType;
-
     private int[] mVoiceActivationState;
 
     private int[] mDataActivationState;
@@ -213,6 +211,9 @@
     private CallAttributes mCallAttributes = new CallAttributes(new PreciseCallState(),
             TelephonyManager.NETWORK_TYPE_UNKNOWN, new CallQuality());
 
+    // network type of the call associated with the mCallAttributes and mCallQuality
+    private int mCallNetworkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
+
     private int[] mSrvccState;
 
     private int mDefaultSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
@@ -374,7 +375,6 @@
         mDataConnectionNetworkType = new int[numPhones];
         mCallIncomingNumber = new String[numPhones];
         mServiceState = new ServiceState[numPhones];
-        mNetworkType = new int[numPhones];
         mVoiceActivationState = new int[numPhones];
         mDataActivationState = new int[numPhones];
         mUserMobileDataState = new boolean[numPhones];
@@ -395,7 +395,6 @@
             mDataActivationState[i] = TelephonyManager.SIM_ACTIVATION_STATE_UNKNOWN;
             mCallIncomingNumber[i] =  "";
             mServiceState[i] =  new ServiceState();
-            mNetworkType[i] = mServiceState[i].getVoiceNetworkType();
             mSignalStrength[i] =  new SignalStrength();
             mUserMobileDataState[i] = false;
             mMessageWaiting[i] =  false;
@@ -997,21 +996,6 @@
             if (validatePhoneId(phoneId)) {
                 mServiceState[phoneId] = state;
 
-                boolean notifyCallAttributes = true;
-                if (mNetworkType[phoneId] != mServiceState[phoneId].getVoiceNetworkType()) {
-                    mNetworkType[phoneId] = state.getVoiceNetworkType();
-                    mCallAttributes = new CallAttributes(mPreciseCallState, mNetworkType[phoneId],
-                            mCallQuality);
-                } else {
-                    // No change to network type, so no need to notify call attributes
-                    notifyCallAttributes = false;
-                }
-
-                if (mCallQuality == null) {
-                    // No call quality reported yet, so no need to notify call attributes
-                    notifyCallAttributes = false;
-                }
-
                 for (Record r : mRecords) {
                     if (VDBG) {
                         log("notifyServiceStateForSubscriber: r=" + r + " subId=" + subId
@@ -1039,14 +1023,6 @@
                             mRemoveList.add(r.binder);
                         }
                     }
-                    if (notifyCallAttributes && r.matchPhoneStateListenerEvent(
-                                    PhoneStateListener.LISTEN_CALL_ATTRIBUTES_CHANGED)) {
-                        try {
-                            r.callback.onCallAttributesChanged(mCallAttributes);
-                        } catch (RemoteException ex) {
-                            mRemoveList.add(r.binder);
-                        }
-                    }
                 }
             } else {
                 log("notifyServiceStateForSubscriber: INVALID phoneId=" + phoneId);
@@ -1573,7 +1549,7 @@
                 log("notifyPreciseCallState: mCallQuality is null, skipping call attributes");
                 notifyCallAttributes = false;
             } else {
-                mCallAttributes = new CallAttributes(mPreciseCallState, mNetworkType[phoneId],
+                mCallAttributes = new CallAttributes(mPreciseCallState, mCallNetworkType,
                         mCallQuality);
             }
 
@@ -1840,16 +1816,16 @@
     }
 
     @Override
-    public void notifyCallQualityChanged(CallQuality callQuality, int phoneId) {
+    public void notifyCallQualityChanged(CallQuality callQuality, int phoneId,
+            int callNetworkType) {
         if (!checkNotifyPermission("notifyCallQualityChanged()")) {
             return;
         }
 
         // merge CallQuality with PreciseCallState and network type
         mCallQuality = callQuality;
-        mCallAttributes = new CallAttributes(mPreciseCallState,
-                mNetworkType[phoneId],
-                callQuality);
+        mCallNetworkType = callNetworkType;
+        mCallAttributes = new CallAttributes(mPreciseCallState, callNetworkType, callQuality);
 
         synchronized (mRecords) {
             TelephonyManager tm = (TelephonyManager) mContext.getSystemService(
@@ -1886,7 +1862,6 @@
                 pw.println("mCallState=" + mCallState[i]);
                 pw.println("mCallIncomingNumber=" + mCallIncomingNumber[i]);
                 pw.println("mServiceState=" + mServiceState[i]);
-                pw.println("mNetworkType=" + mNetworkType[i]);
                 pw.println("mVoiceActivationState= " + mVoiceActivationState[i]);
                 pw.println("mDataActivationState= " + mDataActivationState[i]);
                 pw.println("mUserMobileDataState= " + mUserMobileDataState[i]);
@@ -1900,6 +1875,7 @@
                 pw.println("mImsCallDisconnectCause=" + mImsReasonInfo.get(i).toString());
                 pw.decreaseIndent();
             }
+            pw.println("mCallNetworkType=" + mCallNetworkType);
             pw.println("mPreciseDataConnectionState=" + mPreciseDataConnectionState);
             pw.println("mPreciseCallState=" + mPreciseCallState);
             pw.println("mCallDisconnectCause=" + mCallDisconnectCause);
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 0eec8e9..e18f374 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -2664,7 +2664,7 @@
                     ProcessRecord proc;
                     int procState;
                     int statType;
-                    int pid;
+                    int pid = -1;
                     long lastPssTime;
                     synchronized (ActivityManagerService.this) {
                         if (mPendingPssProcesses.size() <= 0) {
diff --git a/services/core/java/com/android/server/connectivity/Nat464Xlat.java b/services/core/java/com/android/server/connectivity/Nat464Xlat.java
index 9d9b1cf..2646d76 100644
--- a/services/core/java/com/android/server/connectivity/Nat464Xlat.java
+++ b/services/core/java/com/android/server/connectivity/Nat464Xlat.java
@@ -18,19 +18,24 @@
 
 import android.net.ConnectivityManager;
 import android.net.INetd;
+import android.net.InetAddresses;
 import android.net.InterfaceConfiguration;
+import android.net.IpPrefix;
 import android.net.LinkAddress;
 import android.net.LinkProperties;
 import android.net.NetworkInfo;
 import android.net.RouteInfo;
 import android.os.INetworkManagementService;
 import android.os.RemoteException;
+import android.os.ServiceSpecificException;
 import android.util.Slog;
 
+import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.ArrayUtils;
 import com.android.server.net.BaseNetworkObserver;
 
 import java.net.Inet4Address;
+import java.net.Inet6Address;
 import java.util.Objects;
 
 /**
@@ -67,15 +72,16 @@
     private final NetworkAgentInfo mNetwork;
 
     private enum State {
-        IDLE,       // start() not called. Base iface and stacked iface names are null.
-        STARTING,   // start() called. Base iface and stacked iface names are known.
-        RUNNING,    // start() called, and the stacked iface is known to be up.
-        STOPPING;   // stop() called, this Nat464Xlat is still registered as a network observer for
-                    // the stacked interface.
+        IDLE,         // start() not called. Base iface and stacked iface names are null.
+        DISCOVERING,  // same as IDLE, except prefix discovery in progress.
+        STARTING,     // start() called. Base iface and stacked iface names are known.
+        RUNNING,      // start() called, and the stacked iface is known to be up.
     }
 
+    private IpPrefix mNat64Prefix;
     private String mBaseIface;
     private String mIface;
+    private Inet6Address mIPv6Address;
     private State mState = State.IDLE;
 
     public Nat464Xlat(NetworkAgentInfo nai, INetd netd, INetworkManagementService nmService) {
@@ -85,20 +91,51 @@
     }
 
     /**
-     * Determines whether a network requires clat.
+     * Whether to attempt 464xlat on this network. This is true for an IPv6-only network that is
+     * currently connected and where the NetworkAgent has not disabled 464xlat. It is the signal to
+     * enable NAT64 prefix discovery.
+     *
      * @param network the NetworkAgentInfo corresponding to the network.
      * @return true if the network requires clat, false otherwise.
      */
-    public static boolean requiresClat(NetworkAgentInfo nai) {
+    @VisibleForTesting
+    protected static boolean requiresClat(NetworkAgentInfo nai) {
         // TODO: migrate to NetworkCapabilities.TRANSPORT_*.
         final boolean supported = ArrayUtils.contains(NETWORK_TYPES, nai.networkInfo.getType());
         final boolean connected = ArrayUtils.contains(NETWORK_STATES, nai.networkInfo.getState());
-        // We only run clat on networks that don't have a native IPv4 address.
-        final boolean hasIPv4Address =
-                (nai.linkProperties != null) && nai.linkProperties.hasIPv4Address();
-        final boolean skip464xlat =
-                (nai.netMisc() != null) && nai.netMisc().skip464xlat;
-        return supported && connected && !hasIPv4Address && !skip464xlat;
+
+        // Only run clat on networks that have a global IPv6 address and don't have a native IPv4
+        // address.
+        LinkProperties lp = nai.linkProperties;
+        final boolean isIpv6OnlyNetwork = (lp != null) && lp.hasGlobalIPv6Address()
+                && !lp.hasIPv4Address();
+
+        // If the network tells us it doesn't use clat, respect that.
+        final boolean skip464xlat = (nai.netMisc() != null) && nai.netMisc().skip464xlat;
+
+        return supported && connected && isIpv6OnlyNetwork && !skip464xlat;
+    }
+
+    /**
+     * Whether the clat demon should be started on this network now. This is true if requiresClat is
+     * true and a NAT64 prefix has been discovered.
+     *
+     * @param nai the NetworkAgentInfo corresponding to the network.
+     * @return true if the network should start clat, false otherwise.
+     */
+    @VisibleForTesting
+    protected static boolean shouldStartClat(NetworkAgentInfo nai) {
+        LinkProperties lp = nai.linkProperties;
+        return requiresClat(nai) && lp != null && lp.getNat64Prefix() != null;
+    }
+
+    /**
+     * @return true if we have started prefix discovery and not yet stopped it (regardless of
+     * whether it is still running or has succeeded).
+     * A true result corresponds to internal states DISCOVERING, STARTING and RUNNING.
+     */
+    public boolean isPrefixDiscoveryStarted() {
+        return mState == State.DISCOVERING || isStarted();
     }
 
     /**
@@ -106,7 +143,7 @@
      * A true result corresponds to internal states STARTING and RUNNING.
      */
     public boolean isStarted() {
-        return mState != State.IDLE;
+        return (mState == State.STARTING || mState == State.RUNNING);
     }
 
     /**
@@ -124,32 +161,31 @@
     }
 
     /**
-     * @return true if clatd has been stopped.
-     */
-    public boolean isStopping() {
-        return mState == State.STOPPING;
-    }
-
-    /**
      * Start clatd, register this Nat464Xlat as a network observer for the stacked interface,
      * and set internal state.
      */
     private void enterStartingState(String baseIface) {
         try {
             mNMService.registerObserver(this);
-        } catch(RemoteException e) {
-            Slog.e(TAG,
-                    "startClat: Can't register interface observer for clat on " + mNetwork.name());
+        } catch (RemoteException e) {
+            Slog.e(TAG, "Can't register interface observer for clat on " + mNetwork.name());
             return;
         }
+
+        String addrStr = null;
         try {
-            mNetd.clatdStart(baseIface);
-        } catch(RemoteException|IllegalStateException e) {
-            Slog.e(TAG, "Error starting clatd on " + baseIface, e);
+            addrStr = mNetd.clatdStart(baseIface, mNat64Prefix.toString());
+        } catch (RemoteException | ServiceSpecificException e) {
+            Slog.e(TAG, "Error starting clatd on " + baseIface + ": " + e);
         }
         mIface = CLAT_PREFIX + baseIface;
         mBaseIface = baseIface;
         mState = State.STARTING;
+        try {
+            mIPv6Address = (Inet6Address) InetAddresses.parseNumericAddress(addrStr);
+        } catch (ClassCastException | IllegalArgumentException | NullPointerException e) {
+            Slog.e(TAG, "Invalid IPv6 address " + addrStr);
+        }
     }
 
     /**
@@ -161,37 +197,27 @@
     }
 
     /**
-     * Stop clatd, and turn ND offload on if it had been turned off.
-     */
-    private void enterStoppingState() {
-        try {
-            mNetd.clatdStop(mBaseIface);
-        } catch(RemoteException|IllegalStateException e) {
-            Slog.e(TAG, "Error stopping clatd on " + mBaseIface, e);
-        }
-
-        mState = State.STOPPING;
-    }
-
-    /**
      * Unregister as a base observer for the stacked interface, and clear internal state.
      */
-    private void enterIdleState() {
+    private void leaveStartedState() {
         try {
             mNMService.unregisterObserver(this);
-        } catch(RemoteException|IllegalStateException e) {
-            Slog.e(TAG, "Error unregistering clatd observer on " + mBaseIface, e);
+        } catch (RemoteException | IllegalStateException e) {
+            Slog.e(TAG, "Error unregistering clatd observer on " + mBaseIface + ": " + e);
         }
-
         mIface = null;
         mBaseIface = null;
         mState = State.IDLE;
+        if (requiresClat(mNetwork)) {
+            mState = State.DISCOVERING;
+        } else {
+            stopPrefixDiscovery();
+            mState = State.IDLE;
+        }
     }
 
-    /**
-     * Starts the clat daemon.
-     */
-    public void start() {
+    @VisibleForTesting
+    protected void start() {
         if (isStarted()) {
             Slog.e(TAG, "startClat: already started");
             return;
@@ -212,20 +238,82 @@
         enterStartingState(baseIface);
     }
 
-    /**
-     * Stops the clat daemon.
-     */
-    public void stop() {
+    @VisibleForTesting
+    protected void stop() {
         if (!isStarted()) {
+            Slog.e(TAG, "stopClat: already stopped");
             return;
         }
-        Slog.i(TAG, "Stopping clatd on " + mBaseIface);
 
-        boolean wasStarting = isStarting();
-        enterStoppingState();
-        if (wasStarting) {
-            enterIdleState();
+        Slog.i(TAG, "Stopping clatd on " + mBaseIface);
+        try {
+            mNetd.clatdStop(mBaseIface);
+        } catch (RemoteException | ServiceSpecificException e) {
+            Slog.e(TAG, "Error stopping clatd on " + mBaseIface + ": " + e);
         }
+
+        String iface = mIface;
+        boolean wasRunning = isRunning();
+
+        // Change state before updating LinkProperties. handleUpdateLinkProperties ends up calling
+        // fixupLinkProperties, and if at that time the state is still RUNNING, fixupLinkProperties
+        // would wrongly inform ConnectivityService that there is still a stacked interface.
+        leaveStartedState();
+
+        if (wasRunning) {
+            LinkProperties lp = new LinkProperties(mNetwork.linkProperties);
+            lp.removeStackedLink(iface);
+            mNetwork.connService().handleUpdateLinkProperties(mNetwork, lp);
+        }
+    }
+
+    private void startPrefixDiscovery() {
+        try {
+            mNetd.resolverStartPrefix64Discovery(getNetId());
+            mState = State.DISCOVERING;
+        } catch (RemoteException | ServiceSpecificException e) {
+            Slog.e(TAG, "Error starting prefix discovery on netId " + getNetId() + ": " + e);
+        }
+    }
+
+    private void stopPrefixDiscovery() {
+        try {
+            mNetd.resolverStopPrefix64Discovery(getNetId());
+        } catch (RemoteException | ServiceSpecificException e) {
+            Slog.e(TAG, "Error stopping prefix discovery on netId " + getNetId() + ": " + e);
+        }
+    }
+
+    /**
+     * Starts/stops NAT64 prefix discovery and clatd as necessary.
+     */
+    public void update() {
+        // TODO: turn this class into a proper StateMachine. // http://b/126113090
+        if (requiresClat(mNetwork)) {
+            if (!isPrefixDiscoveryStarted()) {
+                startPrefixDiscovery();
+            } else if (shouldStartClat(mNetwork)) {
+                // NAT64 prefix detected. Start clatd.
+                // TODO: support the NAT64 prefix changing after it's been discovered. There is no
+                // need to support this at the moment because it cannot happen without changes to
+                // the Dns64Configuration code in netd.
+                start();
+            } else {
+                // NAT64 prefix removed. Stop clatd and go back into DISCOVERING state.
+                stop();
+            }
+        } else {
+            // Network no longer requires clat. Stop clat and prefix discovery.
+            if (isStarted()) {
+                stop();
+            } else if (isPrefixDiscoveryStarted()) {
+                leaveStartedState();
+            }
+        }
+    }
+
+    public void setNat64Prefix(IpPrefix nat64Prefix) {
+        mNat64Prefix = nat64Prefix;
     }
 
     /**
@@ -234,6 +322,8 @@
      * has no idea that 464xlat is running on top of it.
      */
     public void fixupLinkProperties(LinkProperties oldLp, LinkProperties lp) {
+        lp.setNat64Prefix(mNat64Prefix);
+
         if (!isRunning()) {
             return;
         }
@@ -272,7 +362,7 @@
         try {
             InterfaceConfiguration config = mNMService.getInterfaceConfig(iface);
             return config.getLinkAddress();
-        } catch(RemoteException|IllegalStateException e) {
+        } catch (RemoteException | IllegalStateException e) {
             Slog.e(TAG, "Error getting link properties: " + e);
             return null;
         }
@@ -282,6 +372,20 @@
      * Adds stacked link on base link and transitions to RUNNING state.
      */
     private void handleInterfaceLinkStateChanged(String iface, boolean up) {
+        // TODO: if we call start(), then stop(), then start() again, and the
+        // interfaceLinkStateChanged notification for the first start is delayed past the first
+        // stop, then the code becomes out of sync with system state and will behave incorrectly.
+        //
+        // This is not trivial to fix because:
+        // 1. It is not guaranteed that start() will eventually result in the interface coming up,
+        //    because there could be an error starting clat (e.g., if the interface goes down before
+        //    the packet socket can be bound).
+        // 2. If start is called multiple times, there is nothing in the interfaceLinkStateChanged
+        //    notification that says which start() call the interface was created by.
+        //
+        // Once this code is converted to StateMachine, it will be possible to use deferMessage to
+        // ensure it stays in STARTING state until the interfaceLinkStateChanged notification fires,
+        // and possibly use a timeout (or provide some guarantees at the lower layer) to address #1.
         if (!isStarting() || !up || !Objects.equals(mIface, iface)) {
             return;
         }
@@ -307,20 +411,16 @@
         if (!Objects.equals(mIface, iface)) {
             return;
         }
-        if (!isRunning() && !isStopping()) {
+        if (!isRunning()) {
             return;
         }
 
         Slog.i(TAG, "interface " + iface + " removed");
-        if (!isStopping()) {
-            // Ensure clatd is stopped if stop() has not been called: this likely means that clatd
-            // has crashed.
-            enterStoppingState();
-        }
-        enterIdleState();
-        LinkProperties lp = new LinkProperties(mNetwork.linkProperties);
-        lp.removeStackedLink(iface);
-        mNetwork.connService().handleUpdateLinkProperties(mNetwork, lp);
+        // If we're running, and the interface was removed, then we didn't call stop(), and it's
+        // likely that clatd crashed. Ensure we call stop() so we can start clatd again. Calling
+        // stop() will also update LinkProperties, and if clatd crashed, the LinkProperties update
+        // will cause ConnectivityService to call start() again.
+        stop();
     }
 
     @Override
@@ -337,4 +437,9 @@
     public String toString() {
         return "mBaseIface: " + mBaseIface + ", mIface: " + mIface + ", mState: " + mState;
     }
+
+    @VisibleForTesting
+    protected int getNetId() {
+        return mNetwork.network.netId;
+    }
 }
diff --git a/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java b/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
index d0cff25..f11a0de 100644
--- a/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
+++ b/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
@@ -236,7 +236,7 @@
     public final AsyncChannel asyncChannel;
 
     // Used by ConnectivityService to keep track of 464xlat.
-    public Nat464Xlat clatd;
+    public final Nat464Xlat clatd;
 
     // Set after asynchronous creation of the NetworkMonitor.
     private volatile INetworkMonitor mNetworkMonitor;
@@ -244,8 +244,6 @@
     private static final String TAG = ConnectivityService.class.getSimpleName();
     private static final boolean VDBG = false;
     private final ConnectivityService mConnService;
-    private final INetd mNetd;
-    private final INetworkManagementService mNMS;
     private final Context mContext;
     private final Handler mHandler;
 
@@ -260,9 +258,8 @@
         linkProperties = lp;
         networkCapabilities = nc;
         currentScore = score;
+        clatd = new Nat464Xlat(this, netd, nms);
         mConnService = connService;
-        mNetd = netd;
-        mNMS = nms;
         mContext = context;
         mHandler = handler;
         networkMisc = misc;
@@ -595,32 +592,6 @@
         for (LingerTimer timer : mLingerTimers) { pw.println(timer); }
     }
 
-    public void updateClat(INetworkManagementService netd) {
-        if (Nat464Xlat.requiresClat(this)) {
-            maybeStartClat();
-        } else {
-            maybeStopClat();
-        }
-    }
-
-    /** Ensure clat has started for this network. */
-    public void maybeStartClat() {
-        if (clatd != null && clatd.isStarted()) {
-            return;
-        }
-        clatd = new Nat464Xlat(this, mNetd, mNMS);
-        clatd.start();
-    }
-
-    /** Ensure clat has stopped for this network. */
-    public void maybeStopClat() {
-        if (clatd == null) {
-            return;
-        }
-        clatd.stop();
-        clatd = null;
-    }
-
     public String toString() {
         return "NetworkAgentInfo{ ni{" + networkInfo + "}  "
                 + "network{" + network + "}  nethandle{" + network.getNetworkHandle() + "}  "
diff --git a/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java b/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java
index 1dada92..f4454ae 100644
--- a/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java
+++ b/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java
@@ -146,8 +146,8 @@
         if (isDumpstateBinderServiceRunningLocked()) {
             Slog.w(TAG, "'dumpstate' is already running. Cannot start a new bugreport"
                     + " while another one is currently in progress.");
-            // TODO(b/111441001): Use a new error code; add this to the documentation of the API.
-            reportError(listener, IDumpstateListener.BUGREPORT_ERROR_RUNTIME_ERROR);
+            reportError(listener,
+                    IDumpstateListener.BUGREPORT_ERROR_ANOTHER_REPORT_IN_PROGRESS);
             return;
         }
 
diff --git a/services/core/java/com/android/server/pm/OtaDexoptService.java b/services/core/java/com/android/server/pm/OtaDexoptService.java
index 41eaa24..1c0b78f 100644
--- a/services/core/java/com/android/server/pm/OtaDexoptService.java
+++ b/services/core/java/com/android/server/pm/OtaDexoptService.java
@@ -333,7 +333,7 @@
         PackageDexOptimizer optimizer = new OTADexoptPackageDexOptimizer(
                 collectingInstaller, mPackageManagerService.mInstallLock, mContext);
 
-        optimizer.performDexOpt(pkg, pkg.usesLibraryInfos,
+        optimizer.performDexOpt(pkg,
                 null /* ISAs */,
                 null /* CompilerStats.PackageStats */,
                 mPackageManagerService.getDexManager().getPackageUseInfoOrDefault(pkg.packageName),
diff --git a/services/core/java/com/android/server/pm/PackageDexOptimizer.java b/services/core/java/com/android/server/pm/PackageDexOptimizer.java
index 51575a4..248a2f6 100644
--- a/services/core/java/com/android/server/pm/PackageDexOptimizer.java
+++ b/services/core/java/com/android/server/pm/PackageDexOptimizer.java
@@ -127,7 +127,7 @@
      * <p>Calls to {@link com.android.server.pm.Installer#dexopt} on {@link #mInstaller} are
      * synchronized on {@link #mInstallLock}.
      */
-    int performDexOpt(PackageParser.Package pkg, List<SharedLibraryInfo> sharedLibraries,
+    int performDexOpt(PackageParser.Package pkg,
             String[] instructionSets, CompilerStats.PackageStats packageStats,
             PackageDexUsage.PackageUseInfo packageUseInfo, DexoptOptions options) {
         if (pkg.applicationInfo.uid == -1) {
@@ -140,7 +140,7 @@
         synchronized (mInstallLock) {
             final long acquireTime = acquireWakeLockLI(pkg.applicationInfo.uid);
             try {
-                return performDexOptLI(pkg, sharedLibraries, instructionSets,
+                return performDexOptLI(pkg, instructionSets,
                         packageStats, packageUseInfo, options);
             } finally {
                 releaseWakeLockLI(acquireTime);
@@ -154,9 +154,9 @@
      */
     @GuardedBy("mInstallLock")
     private int performDexOptLI(PackageParser.Package pkg,
-            List<SharedLibraryInfo> sharedLibraries,
             String[] targetInstructionSets, CompilerStats.PackageStats packageStats,
             PackageDexUsage.PackageUseInfo packageUseInfo, DexoptOptions options) {
+        final List<SharedLibraryInfo> sharedLibraries = pkg.usesLibraryInfos;
         final String[] instructionSets = targetInstructionSets != null ?
                 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
         final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 66fc22f..96441c5 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -9452,12 +9452,12 @@
                     options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
             for (PackageParser.Package depPackage : deps) {
                 // TODO: Analyze and investigate if we (should) profile libraries.
-                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
+                pdo.performDexOpt(depPackage, instructionSets,
                         getOrCreateCompilerPackageStats(depPackage),
                     mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
             }
         }
-        return pdo.performDexOpt(p, p.usesLibraryInfos, instructionSets,
+        return pdo.performDexOpt(p, instructionSets,
                 getOrCreateCompilerPackageStats(p),
                 mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
     }
@@ -17806,7 +17806,7 @@
                     REASON_INSTALL,
                     DexoptOptions.DEXOPT_BOOT_COMPLETE |
                     DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
-            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryInfos,
+            mPackageDexOptimizer.performDexOpt(pkg,
                     null /* instructionSets */,
                     getOrCreateCompilerPackageStats(pkg),
                     mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
diff --git a/services/core/java/com/android/server/timezone/RulesManagerService.java b/services/core/java/com/android/server/timezone/RulesManagerService.java
index 4b413e5..296a652 100644
--- a/services/core/java/com/android/server/timezone/RulesManagerService.java
+++ b/services/core/java/com/android/server/timezone/RulesManagerService.java
@@ -16,14 +16,13 @@
 
 package com.android.server.timezone;
 
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.server.EventLogTags;
-import com.android.server.SystemService;
-import com.android.timezone.distro.DistroException;
-import com.android.timezone.distro.DistroVersion;
-import com.android.timezone.distro.StagedDistroOperation;
-import com.android.timezone.distro.TimeZoneDistro;
-import com.android.timezone.distro.installer.TimeZoneDistroInstaller;
+import static android.app.timezone.RulesState.DISTRO_STATUS_INSTALLED;
+import static android.app.timezone.RulesState.DISTRO_STATUS_NONE;
+import static android.app.timezone.RulesState.DISTRO_STATUS_UNKNOWN;
+import static android.app.timezone.RulesState.STAGED_OPERATION_INSTALL;
+import static android.app.timezone.RulesState.STAGED_OPERATION_NONE;
+import static android.app.timezone.RulesState.STAGED_OPERATION_UNINSTALL;
+import static android.app.timezone.RulesState.STAGED_OPERATION_UNKNOWN;
 
 import android.app.timezone.Callback;
 import android.app.timezone.DistroFormatVersion;
@@ -37,6 +36,21 @@
 import android.os.RemoteException;
 import android.util.Slog;
 
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.EventLogTags;
+import com.android.server.SystemService;
+import com.android.timezone.distro.DistroException;
+import com.android.timezone.distro.DistroVersion;
+import com.android.timezone.distro.StagedDistroOperation;
+import com.android.timezone.distro.TimeZoneDistro;
+import com.android.timezone.distro.installer.TimeZoneDistroInstaller;
+
+import libcore.icu.ICU;
+import libcore.timezone.TimeZoneDataFiles;
+import libcore.timezone.TimeZoneFinder;
+import libcore.timezone.TzDataSetVersion;
+import libcore.timezone.ZoneInfoDB;
+
 import java.io.File;
 import java.io.FileDescriptor;
 import java.io.FileInputStream;
@@ -46,18 +60,6 @@
 import java.util.Arrays;
 import java.util.concurrent.Executor;
 import java.util.concurrent.atomic.AtomicBoolean;
-import libcore.icu.ICU;
-import libcore.timezone.TzDataSetVersion;
-import libcore.timezone.TimeZoneFinder;
-import libcore.timezone.ZoneInfoDB;
-
-import static android.app.timezone.RulesState.DISTRO_STATUS_INSTALLED;
-import static android.app.timezone.RulesState.DISTRO_STATUS_NONE;
-import static android.app.timezone.RulesState.DISTRO_STATUS_UNKNOWN;
-import static android.app.timezone.RulesState.STAGED_OPERATION_INSTALL;
-import static android.app.timezone.RulesState.STAGED_OPERATION_NONE;
-import static android.app.timezone.RulesState.STAGED_OPERATION_UNINSTALL;
-import static android.app.timezone.RulesState.STAGED_OPERATION_UNKNOWN;
 
 public final class RulesManagerService extends IRulesManager.Stub {
 
@@ -96,8 +98,6 @@
     @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
     static final String REQUIRED_QUERY_PERMISSION =
             android.Manifest.permission.QUERY_TIME_ZONE_RULES;
-    private static final File SYSTEM_TZ_DATA_FILE = new File("/system/usr/share/zoneinfo/tzdata");
-    private static final File TZ_DATA_DIR = new File("/data/misc/zoneinfo");
 
     private final AtomicBoolean mOperationInProgress = new AtomicBoolean(false);
     private final PermissionHelper mPermissionHelper;
@@ -108,12 +108,14 @@
 
     private static RulesManagerService create(Context context) {
         RulesManagerServiceHelperImpl helper = new RulesManagerServiceHelperImpl(context);
+        File baseVersionFile = new File(TimeZoneDataFiles.getRuntimeModuleTzVersionFile());
+        File tzDataDir = new File(TimeZoneDataFiles.getDataTimeZoneRootDir());
         return new RulesManagerService(
                 helper /* permissionHelper */,
                 helper /* executor */,
                 helper /* intentHelper */,
                 PackageTracker.create(context),
-                new TimeZoneDistroInstaller(TAG, SYSTEM_TZ_DATA_FILE, TZ_DATA_DIR));
+                new TimeZoneDistroInstaller(TAG, baseVersionFile, tzDataDir));
     }
 
     // A constructor that can be used by tests to supply mocked / faked dependencies.
@@ -143,11 +145,11 @@
     /** Like {@link #getRulesState()} without the permission check. */
     private RulesState getRulesStateInternal() {
         synchronized(this) {
-            String systemRulesVersion;
+            TzDataSetVersion baseVersion;
             try {
-                systemRulesVersion = mInstaller.getSystemRulesVersion();
+                baseVersion = mInstaller.readBaseVersion();
             } catch (IOException e) {
-                Slog.w(TAG, "Failed to read system rules", e);
+                Slog.w(TAG, "Failed to read base rules version", e);
                 return null;
             }
 
@@ -196,7 +198,7 @@
                     Slog.w(TAG, "Failed to read staged distro.", e);
                 }
             }
-            return new RulesState(systemRulesVersion, DISTRO_FORMAT_VERSION_SUPPORTED,
+            return new RulesState(baseVersion.rulesVersion, DISTRO_FORMAT_VERSION_SUPPORTED,
                     operationInProgress, stagedOperationStatus, stagedDistroRulesVersion,
                     distroStatus, installedDistroRulesVersion);
         }
@@ -454,13 +456,13 @@
                             pw.println("Operation in progress: " + value);
                             break;
                         }
-                        case 's': {
-                            // Report system image rules version
+                        case 'b': {
+                            // Report base rules version
                             String value = "Unknown";
                             if (rulesState != null) {
-                                value = rulesState.getSystemRulesVersion();
+                                value = rulesState.getBaseRulesVersion();
                             }
-                            pw.println("System rules version: " + value);
+                            pw.println("Base rules version: " + value);
                             break;
                         }
                         case 'c': {
diff --git a/services/net/java/android/net/ip/RouterAdvertisementDaemon.java b/services/net/java/android/net/ip/RouterAdvertisementDaemon.java
index 8e3023b..339607b 100644
--- a/services/net/java/android/net/ip/RouterAdvertisementDaemon.java
+++ b/services/net/java/android/net/ip/RouterAdvertisementDaemon.java
@@ -275,6 +275,9 @@
 
     public void stop() {
         closeSocket();
+        // Wake up mMulticastTransmitter thread to interrupt a potential 1 day sleep before
+        // the thread's termination.
+        maybeNotifyMulticastTransmitter();
         mMulticastTransmitter = null;
         mUnicastResponder = null;
     }
diff --git a/services/tests/servicestests/src/com/android/server/timezone/RulesManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/timezone/RulesManagerServiceTest.java
index 1b106dd..5c6fe0f 100644
--- a/services/tests/servicestests/src/com/android/server/timezone/RulesManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/timezone/RulesManagerServiceTest.java
@@ -16,34 +16,9 @@
 
 package com.android.server.timezone;
 
-import com.android.timezone.distro.DistroVersion;
-import com.android.timezone.distro.StagedDistroOperation;
-import com.android.timezone.distro.TimeZoneDistro;
-import com.android.timezone.distro.installer.TimeZoneDistroInstaller;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import android.app.timezone.Callback;
-import android.app.timezone.DistroRulesVersion;
-import android.app.timezone.ICallback;
-import android.app.timezone.RulesManager;
-import android.app.timezone.RulesState;
-import android.os.ParcelFileDescriptor;
-
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.concurrent.Executor;
-import javax.annotation.Nullable;
-
-import libcore.io.IoUtils;
-import libcore.timezone.TzDataSetVersion;
-
 import static com.android.server.timezone.RulesManagerService.REQUIRED_QUERY_PERMISSION;
 import static com.android.server.timezone.RulesManagerService.REQUIRED_UPDATER_PERMISSION;
+
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
@@ -61,11 +36,43 @@
 import static org.mockito.Mockito.verifyZeroInteractions;
 import static org.mockito.Mockito.when;
 
+import android.app.timezone.Callback;
+import android.app.timezone.DistroRulesVersion;
+import android.app.timezone.ICallback;
+import android.app.timezone.RulesManager;
+import android.app.timezone.RulesState;
+import android.os.ParcelFileDescriptor;
+
+import com.android.timezone.distro.DistroVersion;
+import com.android.timezone.distro.StagedDistroOperation;
+import com.android.timezone.distro.TimeZoneDistro;
+import com.android.timezone.distro.installer.TimeZoneDistroInstaller;
+
+import libcore.io.IoUtils;
+import libcore.timezone.TzDataSetVersion;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.concurrent.Executor;
+
+import javax.annotation.Nullable;
+
 /**
  * White box interaction / unit testing of the {@link RulesManagerService}.
  */
 public class RulesManagerServiceTest {
 
+    private static final int CURRENT_FORMAT_MAJOR_VERSION =
+            TzDataSetVersion.currentFormatMajorVersion();
+    private static final int CURRENT_FORMAT_MINOR_VERSION =
+            TzDataSetVersion.currentFormatMinorVersion();
+
     private RulesManagerService mRulesManagerService;
 
     private FakeExecutor mFakeExecutor;
@@ -116,8 +123,8 @@
     }
 
     @Test
-    public void getRulesState_systemRulesError() throws Exception {
-        configureDeviceCannotReadSystemRulesVersion();
+    public void getRulesState_baseVersionError() throws Exception {
+        configureDeviceCannotReadBaseVersion();
 
         assertNull(mRulesManagerService.getRulesState());
     }
@@ -126,18 +133,18 @@
     public void getRulesState_stagedInstall() throws Exception {
         configureCallerHasPermission();
 
-        configureDeviceSystemRulesVersion("2016a");
+        configureDeviceBaseVersion("2016a");
 
         DistroVersion stagedDistroVersion = new DistroVersion(
-                TzDataSetVersion.currentFormatMajorVersion(),
-                TzDataSetVersion.currentFormatMinorVersion() - 1,
+                CURRENT_FORMAT_MAJOR_VERSION,
+                CURRENT_FORMAT_MINOR_VERSION - 1,
                 "2016c",
-                3);
+                3 /* revision */);
         configureStagedInstall(stagedDistroVersion);
 
         DistroVersion installedDistroVersion = new DistroVersion(
-                TzDataSetVersion.currentFormatMajorVersion(),
-                TzDataSetVersion.currentFormatMinorVersion() - 1,
+                CURRENT_FORMAT_MAJOR_VERSION,
+                CURRENT_FORMAT_MINOR_VERSION - 1,
                 "2016b",
                 4);
         configureInstalledDistroVersion(installedDistroVersion);
@@ -158,13 +165,13 @@
     public void getRulesState_nothingStaged() throws Exception {
         configureCallerHasPermission();
 
-        configureDeviceSystemRulesVersion("2016a");
+        configureDeviceBaseVersion("2016a");
 
         configureNoStagedOperation();
 
         DistroVersion installedDistroVersion = new DistroVersion(
-                TzDataSetVersion.currentFormatMajorVersion(),
-                TzDataSetVersion.currentFormatMinorVersion() - 1,
+                CURRENT_FORMAT_MAJOR_VERSION,
+                CURRENT_FORMAT_MINOR_VERSION - 1,
                 "2016b",
                 4);
         configureInstalledDistroVersion(installedDistroVersion);
@@ -183,13 +190,13 @@
     public void getRulesState_uninstallStaged() throws Exception {
         configureCallerHasPermission();
 
-        configureDeviceSystemRulesVersion("2016a");
+        configureDeviceBaseVersion("2016a");
 
         configureStagedUninstall();
 
         DistroVersion installedDistroVersion = new DistroVersion(
-                TzDataSetVersion.currentFormatMajorVersion(),
-                TzDataSetVersion.currentFormatMinorVersion() - 1,
+                CURRENT_FORMAT_MAJOR_VERSION,
+                CURRENT_FORMAT_MINOR_VERSION - 1,
                 "2016b",
                 4);
         configureInstalledDistroVersion(installedDistroVersion);
@@ -208,8 +215,8 @@
     public void getRulesState_installedRulesError() throws Exception {
         configureCallerHasPermission();
 
-        String systemRulesVersion = "2016a";
-        configureDeviceSystemRulesVersion(systemRulesVersion);
+        String baseRulesVersion = "2016a";
+        configureDeviceBaseVersion(baseRulesVersion);
 
         configureStagedUninstall();
         configureDeviceCannotReadInstalledDistroVersion();
@@ -226,14 +233,14 @@
     public void getRulesState_stagedRulesError() throws Exception {
         configureCallerHasPermission();
 
-        String systemRulesVersion = "2016a";
-        configureDeviceSystemRulesVersion(systemRulesVersion);
+        String baseRulesVersion = "2016a";
+        configureDeviceBaseVersion(baseRulesVersion);
 
         configureDeviceCannotReadStagedDistroOperation();
 
         DistroVersion installedDistroVersion = new DistroVersion(
-                TzDataSetVersion.currentFormatMajorVersion(),
-                TzDataSetVersion.currentFormatMinorVersion() - 1,
+                CURRENT_FORMAT_MAJOR_VERSION,
+                CURRENT_FORMAT_MINOR_VERSION - 1,
                 "2016b",
                 4);
         configureInstalledDistroVersion(installedDistroVersion);
@@ -252,13 +259,13 @@
     public void getRulesState_noInstalledRules() throws Exception {
         configureCallerHasPermission();
 
-        String systemRulesVersion = "2016a";
-        configureDeviceSystemRulesVersion(systemRulesVersion);
+        String baseRulesVersion = "2016a";
+        configureDeviceBaseVersion(baseRulesVersion);
         configureNoStagedOperation();
         configureInstalledDistroVersion(null);
 
         RulesState expectedRuleState = new RulesState(
-                systemRulesVersion, RulesManagerService.DISTRO_FORMAT_VERSION_SUPPORTED,
+                baseRulesVersion, RulesManagerService.DISTRO_FORMAT_VERSION_SUPPORTED,
                 false /* operationInProgress */,
                 RulesState.STAGED_OPERATION_NONE, null /* stagedDistroRulesVersion */,
                 RulesState.DISTRO_STATUS_NONE, null /* installedDistroRulesVersion */);
@@ -269,15 +276,15 @@
     public void getRulesState_operationInProgress() throws Exception {
         configureCallerHasPermission();
 
-        String systemRulesVersion = "2016a";
+        String baseRulesVersion = "2016a";
         String installedRulesVersion = "2016b";
         int revision = 3;
 
-        configureDeviceSystemRulesVersion(systemRulesVersion);
+        configureDeviceBaseVersion(baseRulesVersion);
 
         DistroVersion installedDistroVersion = new DistroVersion(
-                TzDataSetVersion.currentFormatMajorVersion(),
-                TzDataSetVersion.currentFormatMinorVersion() - 1,
+                CURRENT_FORMAT_MAJOR_VERSION,
+                CURRENT_FORMAT_MINOR_VERSION - 1,
                 installedRulesVersion,
                 revision);
         configureInstalledDistroVersion(installedDistroVersion);
@@ -297,7 +304,7 @@
         DistroRulesVersion expectedInstalledDistroRulesVersion =
                 new DistroRulesVersion(installedRulesVersion, revision);
         RulesState expectedRuleState = new RulesState(
-                systemRulesVersion, RulesManagerService.DISTRO_FORMAT_VERSION_SUPPORTED,
+                baseRulesVersion, RulesManagerService.DISTRO_FORMAT_VERSION_SUPPORTED,
                 true /* operationInProgress */,
                 RulesState.STAGED_OPERATION_UNKNOWN, null /* stagedDistroRulesVersion */,
                 RulesState.DISTRO_STATUS_INSTALLED, expectedInstalledDistroRulesVersion);
@@ -858,11 +865,20 @@
                 .thenReturn(true);
 
         // Set up the mocks to return (arbitrary) information about the current device state.
-        when(mMockTimeZoneDistroInstaller.getSystemRulesVersion()).thenReturn("2017a");
-        when(mMockTimeZoneDistroInstaller.getInstalledDistroVersion()).thenReturn(
-                new DistroVersion(2, 3, "2017b", 4));
+        TzDataSetVersion baseVersion = new TzDataSetVersion(
+                CURRENT_FORMAT_MAJOR_VERSION, CURRENT_FORMAT_MINOR_VERSION, "2017a",
+                1 /* revision */);
+        when(mMockTimeZoneDistroInstaller.readBaseVersion()).thenReturn(baseVersion);
+        DistroVersion installedDistroVersion = new DistroVersion(
+                CURRENT_FORMAT_MAJOR_VERSION, CURRENT_FORMAT_MINOR_VERSION, "2017b",
+                4 /* revision */);
+        when(mMockTimeZoneDistroInstaller.getInstalledDistroVersion())
+                .thenReturn(installedDistroVersion);
+        DistroVersion stagedDistroVersion = new DistroVersion(
+                CURRENT_FORMAT_MAJOR_VERSION, CURRENT_FORMAT_MINOR_VERSION, "2017c",
+                7 /* revision */);
         when(mMockTimeZoneDistroInstaller.getStagedDistroOperation()).thenReturn(
-                StagedDistroOperation.install(new DistroVersion(5, 6, "2017c", 7)));
+                StagedDistroOperation.install(stagedDistroVersion));
 
         // Do the dump call.
         String dumpedOutput = doDumpCallAndCapture(rulesManagerService, args);
@@ -973,8 +989,11 @@
         return new CheckToken(1, new PackageVersions(1, 1));
     }
 
-    private void configureDeviceSystemRulesVersion(String systemRulesVersion) throws Exception {
-        when(mMockTimeZoneDistroInstaller.getSystemRulesVersion()).thenReturn(systemRulesVersion);
+    private void configureDeviceBaseVersion(String baseRulesVersion) throws Exception {
+        TzDataSetVersion tzDataSetVersion = new TzDataSetVersion(
+                CURRENT_FORMAT_MAJOR_VERSION, CURRENT_FORMAT_MINOR_VERSION, baseRulesVersion,
+                1 /* revision */);
+        when(mMockTimeZoneDistroInstaller.readBaseVersion()).thenReturn(tzDataSetVersion);
     }
 
     private void configureInstalledDistroVersion(@Nullable DistroVersion installedDistroVersion)
@@ -1002,8 +1021,8 @@
                 .thenThrow(new IOException("Simulated failure"));
     }
 
-    private void configureDeviceCannotReadSystemRulesVersion() throws Exception {
-        when(mMockTimeZoneDistroInstaller.getSystemRulesVersion())
+    private void configureDeviceCannotReadBaseVersion() throws Exception {
+        when(mMockTimeZoneDistroInstaller.readBaseVersion())
                 .thenThrow(new IOException("Simulated failure"));
     }
 
diff --git a/telecomm/java/android/telecom/CallIdentification.java b/telecomm/java/android/telecom/CallIdentification.java
index 87834fd..cde7f60 100644
--- a/telecomm/java/android/telecom/CallIdentification.java
+++ b/telecomm/java/android/telecom/CallIdentification.java
@@ -45,13 +45,13 @@
      * {@link CallIdentification} for a screened call.
      */
     public static class Builder {
-        private String mName;
-        private String mDescription;
-        private String mDetails;
+        private CharSequence mName;
+        private CharSequence mDescription;
+        private CharSequence mDetails;
         private Icon mPhoto;
         private int mNuisanceConfidence = CallIdentification.CONFIDENCE_UNKNOWN;
         private String mPackageName;
-        private String mAppName;
+        private CharSequence mAppName;
 
         /**
          * Default builder constructor.
@@ -67,7 +67,7 @@
          * @param callIdAppName The app name.
          * @hide
          */
-        public Builder(String callIdPackageName, String callIdAppName) {
+        public Builder(String callIdPackageName, CharSequence callIdAppName) {
             mPackageName = callIdPackageName;
             mAppName = callIdAppName;
         }
@@ -80,7 +80,7 @@
          * @param name The name associated with the call, or {@code null} if none is provided.
          * @return Builder instance.
          */
-        public Builder setName(@Nullable String name) {
+        public Builder setName(@Nullable CharSequence name) {
             mName = name;
             return this;
         }
@@ -97,7 +97,7 @@
          * @param description The call description, or {@code null} if none is provided.
          * @return Builder instance.
          */
-        public Builder setDescription(@Nullable String description) {
+        public Builder setDescription(@Nullable CharSequence description) {
             mDescription = description;
             return this;
         }
@@ -114,7 +114,7 @@
          * @param details The call details, or {@code null} if none is provided.
          * @return Builder instance.
          */
-        public Builder setDetails(@Nullable String details) {
+        public Builder setDetails(@Nullable CharSequence details) {
             mDetails = details;
             return this;
         }
@@ -241,10 +241,10 @@
      *                             call identification.
      * @hide
      */
-    private CallIdentification(@Nullable String name, @Nullable String description,
-            @Nullable String details, @Nullable Icon photo,
+    private CallIdentification(@Nullable CharSequence name, @Nullable CharSequence description,
+            @Nullable CharSequence details, @Nullable Icon photo,
             @NuisanceConfidence int nuisanceConfidence, @NonNull String callScreeningPackageName,
-            @NonNull String callScreeningAppName) {
+            @NonNull CharSequence callScreeningAppName) {
         mName = name;
         mDescription = description;
         mDetails = details;
@@ -254,13 +254,13 @@
         mCallScreeningPackageName = callScreeningPackageName;
     }
 
-    private String mName;
-    private String mDescription;
-    private String mDetails;
+    private CharSequence mName;
+    private CharSequence mDescription;
+    private CharSequence mDetails;
     private Icon mPhoto;
     private int mNuisanceConfidence;
     private String mCallScreeningPackageName;
-    private String mCallScreeningAppName;
+    private CharSequence mCallScreeningAppName;
 
     @Override
     public int describeContents() {
@@ -269,13 +269,13 @@
 
     @Override
     public void writeToParcel(Parcel parcel, int i) {
-        parcel.writeString(mName);
-        parcel.writeString(mDescription);
-        parcel.writeString(mDetails);
+        parcel.writeCharSequence(mName);
+        parcel.writeCharSequence(mDescription);
+        parcel.writeCharSequence(mDetails);
         parcel.writeParcelable(mPhoto, 0);
         parcel.writeInt(mNuisanceConfidence);
         parcel.writeString(mCallScreeningPackageName);
-        parcel.writeString(mCallScreeningAppName);
+        parcel.writeCharSequence(mCallScreeningAppName);
     }
 
     /**
@@ -286,13 +286,13 @@
 
                 @Override
                 public CallIdentification createFromParcel(Parcel source) {
-                    String name = source.readString();
-                    String description = source.readString();
-                    String details = source.readString();
+                    CharSequence name = source.readCharSequence();
+                    CharSequence description = source.readCharSequence();
+                    CharSequence details = source.readCharSequence();
                     Icon photo = source.readParcelable(ClassLoader.getSystemClassLoader());
                     int nuisanceConfidence = source.readInt();
                     String callScreeningPackageName = source.readString();
-                    String callScreeningAppName = source.readString();
+                    CharSequence callScreeningAppName = source.readCharSequence();
                     return new CallIdentification(name, description, details, photo,
                             nuisanceConfidence, callScreeningPackageName, callScreeningAppName);
                 }
@@ -311,7 +311,7 @@
      *
      * @return The name associated with the number, or {@code null} if none was provided.
      */
-    public final @Nullable String getName() {
+    public final @Nullable CharSequence getName() {
         return mName;
     }
 
@@ -325,7 +325,7 @@
      *
      * @return The call description, or {@code null} if none was provided.
      */
-    public final @Nullable String getDescription() {
+    public final @Nullable CharSequence getDescription() {
         return mDescription;
     }
 
@@ -340,7 +340,7 @@
      *
      * @return The call details, or {@code null} if none was provided.
      */
-    public final @Nullable String getDetails() {
+    public final @Nullable CharSequence getDetails() {
         return mDetails;
     }
 
@@ -363,8 +363,7 @@
      *
      * @return The nuisance confidence.
      */
-    public final @NuisanceConfidence
-    int getNuisanceConfidence() {
+    public final @NuisanceConfidence int getNuisanceConfidence() {
         return mNuisanceConfidence;
     }
 
@@ -387,7 +386,7 @@
      *
      * @return The name of the app.
      */
-    public final @NonNull String getCallScreeningAppName() {
+    public final @NonNull CharSequence getCallScreeningAppName() {
         return mCallScreeningAppName;
     }
 
@@ -407,7 +406,7 @@
      * @param callScreeningAppName The app name.
      * @hide
      */
-    public void setCallScreeningAppName(@NonNull String callScreeningAppName) {
+    public void setCallScreeningAppName(@NonNull CharSequence callScreeningAppName) {
         mCallScreeningAppName = callScreeningAppName;
     }
 
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index 5c5d856..aef3dbf 100644
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -2800,9 +2800,9 @@
         /* Default value is 1024 kbps */
         sDefaults.putInt(KEY_OPPORTUNISTIC_NETWORK_ENTRY_THRESHOLD_BANDWIDTH_INT, 1024);
         /* Default value is 10 seconds */
-        sDefaults.putInt(KEY_OPPORTUNISTIC_NETWORK_ENTRY_OR_EXIT_HYSTERESIS_TIME_LONG, 10000);
+        sDefaults.putLong(KEY_OPPORTUNISTIC_NETWORK_ENTRY_OR_EXIT_HYSTERESIS_TIME_LONG, 10000);
         /* Default value is 10 seconds. */
-        sDefaults.putInt(KEY_OPPORTUNISTIC_NETWORK_DATA_SWITCH_HYSTERESIS_TIME_LONG, 10000);
+        sDefaults.putLong(KEY_OPPORTUNISTIC_NETWORK_DATA_SWITCH_HYSTERESIS_TIME_LONG, 10000);
     }
 
     /**
diff --git a/telephony/java/android/telephony/CellSignalStrength.java b/telephony/java/android/telephony/CellSignalStrength.java
index 7d07a73..aaf6c71 100644
--- a/telephony/java/android/telephony/CellSignalStrength.java
+++ b/telephony/java/android/telephony/CellSignalStrength.java
@@ -119,7 +119,7 @@
     /** @hide */
     protected static final int getAsuFromRssiDbm(int dbm) {
         if (dbm == CellInfo.UNAVAILABLE) return 99;
-        return (dbm / 2) + 113;
+        return (dbm + 113) / 2;
     }
 
     // Range for RSCP in ASU (0-96, 255) as defined in TS 27.007 8.69
diff --git a/telephony/java/android/telephony/DataSpecificRegistrationStates.java b/telephony/java/android/telephony/DataSpecificRegistrationStates.java
index d6a8065..c3387f3 100644
--- a/telephony/java/android/telephony/DataSpecificRegistrationStates.java
+++ b/telephony/java/android/telephony/DataSpecificRegistrationStates.java
@@ -1,5 +1,7 @@
 package android.telephony;
 
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 
@@ -10,14 +12,17 @@
  * Class that stores information specific to data network registration.
  * @hide
  */
-public class DataSpecificRegistrationStates implements Parcelable{
+@SystemApi
+public final class DataSpecificRegistrationStates implements Parcelable{
     /**
+     * @hide
      * The maximum number of simultaneous Data Calls that
      * must be established using setupDataCall().
      */
     public final int maxDataCalls;
 
     /**
+     * @hide
      * Indicates if the use of dual connectivity with NR is restricted.
      * Reference: 3GPP TS 24.301 v15.03 section 9.3.3.12A.
      */
@@ -25,7 +30,7 @@
 
     /**
      * Indicates if NR is supported by the selected PLMN.
-     *
+     * @hide
      * {@code true} if the bit N is in the PLMN-InfoList-r15 is true and the selected PLMN is
      * present in plmn-IdentityList at position N.
      * Reference: 3GPP TS 36.331 v15.2.2 section 6.3.1 PLMN-InfoList-r15.
@@ -34,6 +39,7 @@
     public final boolean isNrAvailable;
 
     /**
+     * @hide
      * Indicates that if E-UTRA-NR Dual Connectivity (EN-DC) is supported by the primary serving
      * cell.
      *
@@ -47,8 +53,11 @@
     /**
      * Provides network support info for LTE VoPS and LTE Emergency bearer support
      */
-    public final LteVopsSupportInfo lteVopsSupportInfo;
+    private final LteVopsSupportInfo lteVopsSupportInfo;
 
+    /**
+     * @hide
+     */
     DataSpecificRegistrationStates(
             int maxDataCalls, boolean isDcNrRestricted, boolean isNrAvailable,
             boolean isEnDcAvailable, LteVopsSupportInfo lteVops) {
@@ -126,4 +135,12 @@
                     return new DataSpecificRegistrationStates[size];
                 }
             };
+
+    /**
+     * @return LteVopsSupportInfo
+     */
+    @NonNull
+    public LteVopsSupportInfo getLteVopsSupportInfo() {
+        return lteVopsSupportInfo;
+    }
 }
diff --git a/telephony/java/android/telephony/DisconnectCause.java b/telephony/java/android/telephony/DisconnectCause.java
index f53cb82..6e839ab 100644
--- a/telephony/java/android/telephony/DisconnectCause.java
+++ b/telephony/java/android/telephony/DisconnectCause.java
@@ -26,7 +26,7 @@
  * @hide
  */
 @SystemApi
-public class DisconnectCause {
+public final class DisconnectCause {
 
     /** The disconnect cause is not valid (Not received a disconnect cause) */
     public static final int NOT_VALID                      = -1;
diff --git a/telephony/java/android/telephony/NetworkRegistrationState.java b/telephony/java/android/telephony/NetworkRegistrationState.java
index 6e6d59e..84d6628 100644
--- a/telephony/java/android/telephony/NetworkRegistrationState.java
+++ b/telephony/java/android/telephony/NetworkRegistrationState.java
@@ -349,7 +349,7 @@
     }
 
     /**
-     * @hide
+     * @return Data registration related info
      */
     @Nullable
     public DataSpecificRegistrationStates getDataSpecificStates() {
diff --git a/telephony/java/android/telephony/PhoneStateListener.java b/telephony/java/android/telephony/PhoneStateListener.java
index 3ce646c..da92730 100644
--- a/telephony/java/android/telephony/PhoneStateListener.java
+++ b/telephony/java/android/telephony/PhoneStateListener.java
@@ -176,26 +176,21 @@
 
     /**
      * Listen for {@link PreciseCallState.State} of ringing, background and foreground calls.
-     * {@more}
-     * Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
-     * READ_PRECISE_PHONE_STATE}
      *
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
     public static final int LISTEN_PRECISE_CALL_STATE                       = 0x00000800;
 
     /**
      * Listen for {@link PreciseDataConnectionState} on the data connection (cellular).
      *
-     * {@more}
-     * Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
-     * READ_PRECISE_PHONE_STATE}
-     *
      * @see #onPreciseDataConnectionStateChanged
      *
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
     public static final int LISTEN_PRECISE_DATA_CONNECTION_STATE            = 0x00001000;
 
@@ -328,12 +323,10 @@
     /**
      * Listen for call disconnect causes which contains {@link DisconnectCause} and
      * {@link PreciseDisconnectCause}.
-     * {@more}
-     * Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
-     * READ_PRECISE_PHONE_STATE}
      *
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
     public static final int LISTEN_CALL_DISCONNECT_CAUSES                  = 0x02000000;
 
@@ -353,13 +346,10 @@
      * Listen for IMS call disconnect causes which contains
      * {@link android.telephony.ims.ImsReasonInfo}
      *
-     * {@more}
-     * Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
-     * READ_PRECISE_PHONE_STATE}
-     *
      * @see #onImsCallDisconnectCauseChanged(ImsReasonInfo)
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
     public static final int LISTEN_IMS_CALL_DISCONNECT_CAUSES              = 0x08000000;
 
@@ -576,8 +566,9 @@
      * @param callState {@link PreciseCallState}
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
-    public void onPreciseCallStateChanged(PreciseCallState callState) {
+    public void onPreciseCallStateChanged(@NonNull PreciseCallState callState) {
         // default implementation empty
     }
 
@@ -588,6 +579,7 @@
      *
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
     public void onCallDisconnectCauseChanged(int disconnectCause, int preciseDisconnectCause) {
         // default implementation empty
@@ -599,6 +591,7 @@
      *
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
     public void onImsCallDisconnectCauseChanged(@NonNull ImsReasonInfo imsReasonInfo) {
         // default implementation empty
@@ -610,6 +603,7 @@
      *
      * @hide
      */
+    @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
     @SystemApi
     public void onPreciseDataConnectionStateChanged(
             PreciseDataConnectionState dataConnectionState) {
diff --git a/telephony/java/android/telephony/PreciseDisconnectCause.java b/telephony/java/android/telephony/PreciseDisconnectCause.java
index af88748..54980a2 100644
--- a/telephony/java/android/telephony/PreciseDisconnectCause.java
+++ b/telephony/java/android/telephony/PreciseDisconnectCause.java
@@ -23,7 +23,7 @@
  * @hide
  */
 @SystemApi
-public class PreciseDisconnectCause {
+public final class PreciseDisconnectCause {
 
     /** The disconnect cause is not valid (Not received a disconnect cause).*/
     public static final int NOT_VALID                                        = -1;
diff --git a/telephony/java/android/telephony/ServiceState.java b/telephony/java/android/telephony/ServiceState.java
index a1aee6d..3dc1199 100644
--- a/telephony/java/android/telephony/ServiceState.java
+++ b/telephony/java/android/telephony/ServiceState.java
@@ -1569,6 +1569,17 @@
     /** @hide */
     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
     public @TelephonyManager.NetworkType int getDataNetworkType() {
+        final NetworkRegistrationState iwlanRegState = getNetworkRegistrationState(
+                NetworkRegistrationState.DOMAIN_PS, AccessNetworkConstants.TransportType.WLAN);
+        if (iwlanRegState != null
+                && iwlanRegState.getRegState() == NetworkRegistrationState.REG_STATE_HOME) {
+            // If the device is on IWLAN, return IWLAN as the network type. This is to simulate the
+            // behavior of legacy mode device. In the future caller should use
+            // getNetworkRegistrationState() to retrieve the actual data network type on cellular
+            // or on IWLAN.
+            return iwlanRegState.getAccessNetworkTechnology();
+        }
+
         final NetworkRegistrationState regState = getNetworkRegistrationState(
                 NetworkRegistrationState.DOMAIN_PS, AccessNetworkConstants.TransportType.WWAN);
         if (regState != null) {
diff --git a/telephony/java/android/telephony/SignalStrength.java b/telephony/java/android/telephony/SignalStrength.java
index d2ae106..d461bd0 100644
--- a/telephony/java/android/telephony/SignalStrength.java
+++ b/telephony/java/android/telephony/SignalStrength.java
@@ -215,13 +215,52 @@
      * @see android.telephony#CellSignalStrengthGsm
      */
     public @NonNull List<CellSignalStrength> getCellSignalStrengths() {
-        List<CellSignalStrength> cssList = new ArrayList<>(2); // Usually have 2 or fewer elems
-        if (mLte.isValid()) cssList.add(mLte);
-        if (mCdma.isValid()) cssList.add(mCdma);
-        if (mTdscdma.isValid()) cssList.add(mTdscdma);
-        if (mWcdma.isValid()) cssList.add(mWcdma);
-        if (mGsm.isValid()) cssList.add(mGsm);
-        if (mNr.isValid()) cssList.add(mNr);
+        return getCellSignalStrengths(CellSignalStrength.class);
+    }
+
+    /**
+     * Returns a List of CellSignalStrength Components of this SignalStrength Report.
+     *
+     * Use this API to access underlying
+     * {@link android.telephony#CellSignalStrength CellSignalStrength} objects that provide more
+     * granular information about the SignalStrength report. Only valid (non-empty)
+     * CellSignalStrengths will be returned. The order of any returned elements is not guaranteed,
+     * and the list may contain more than one instance of a CellSignalStrength type.
+     *
+     * @param clazz a class type that extends
+     *        {@link android.telephony.CellSignalStrength CellSignalStrength} to filter possible
+     *        return values.
+     * @return a List of CellSignalStrength or an empty List if there are no valid measurements.
+     *
+     * @see android.telephony#CellSignalStrength
+     * @see android.telephony#CellSignalStrengthNr
+     * @see android.telephony#CellSignalStrengthLte
+     * @see android.telephony#CellSignalStrengthTdscdma
+     * @see android.telephony#CellSignalStrengthWcdma
+     * @see android.telephony#CellSignalStrengthCdma
+     * @see android.telephony#CellSignalStrengthGsm
+     */
+    public <T extends CellSignalStrength> @NonNull List<T> getCellSignalStrengths(
+            @NonNull Class<T> clazz) {
+        List<T> cssList = new ArrayList<>(2); // Usually have 2 or fewer elems
+        if (mLte.isValid() && clazz.isAssignableFrom(CellSignalStrengthLte.class)) {
+            cssList.add((T) mLte);
+        }
+        if (mCdma.isValid() && clazz.isAssignableFrom(CellSignalStrengthCdma.class)) {
+            cssList.add((T) mCdma);
+        }
+        if (mTdscdma.isValid() && clazz.isAssignableFrom(CellSignalStrengthTdscdma.class)) {
+            cssList.add((T) mTdscdma);
+        }
+        if (mWcdma.isValid() && clazz.isAssignableFrom(CellSignalStrengthWcdma.class)) {
+            cssList.add((T) mWcdma);
+        }
+        if (mGsm.isValid() && clazz.isAssignableFrom(CellSignalStrengthGsm.class)) {
+            cssList.add((T) mGsm);
+        }
+        if (mNr.isValid() && clazz.isAssignableFrom(CellSignalStrengthNr.class)) {
+            cssList.add((T) mNr);
+        }
         return cssList;
     }
 
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index 6704473..29a305e 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -1355,6 +1355,26 @@
      * Intent sent when an error occurs that debug tools should log and possibly take further
      * action such as capturing vendor-specific logs.
      *
+     * A privileged application that reads these events should take appropriate vendor-specific
+     * action to record the event and collect further information to assist in analysis, debugging,
+     * and resolution of any associated issue.
+     *
+     * <p>This event should not be used for generic logging or diagnostic monitoring purposes and
+     * should generally be sent at a low rate. Instead, this mechanism should be used for the
+     * framework to notify a debugging application that an event (such as a bug) has occured
+     * within the framework if that event should trigger the collection and preservation of other
+     * more detailed device state for debugging.
+     *
+     * <p>At most one application can receive these events and should register a receiver in
+     * in the application manifest. For performance reasons, if no application to receive these
+     * events is detected at boot, then these events will not be sent.
+     *
+     * <p>Each event will include an {@link EXTRA_DEBUG_EVENT_ID} that will uniquely identify the
+     * event that has occurred. Each event will be sent to the diagnostic monitor only once per
+     * boot cycle (as another optimization).
+     *
+     * @see #EXTRA_DEBUG_EVENT_ID
+     * @see #EXTRA_DEBUG_EVENT_DESCRIPTION
      * @hide
      */
     @SystemApi
@@ -1362,21 +1382,23 @@
     public static final String ACTION_DEBUG_EVENT = "android.telephony.action.DEBUG_EVENT";
 
     /**
-     * An arbitrary ParcelUuid which should be consistent for each occurrence of the same event.
+     * An arbitrary ParcelUuid which should be consistent for each occurrence of a DebugEvent.
      *
-     * This field must be included in all events.
+     * This field must be included in all {@link ACTION_DEBUG_EVENT} events.
      *
+     * @see #ACTION_DEBUG_EVENT
      * @hide
      */
     @SystemApi
     public static final String EXTRA_DEBUG_EVENT_ID = "android.telephony.extra.DEBUG_EVENT_ID";
 
     /**
-     * A freeform string description of the event.
+     * A freeform string description of the DebugEvent.
      *
-     * This field is optional for all events and as a guideline should not exceed 80 characters
-     * and should be as short as possible to convey the essence of the event.
+     * This field is optional for all {@link ACTION_DEBUG_EVENT}s, as a guideline should not
+     * exceed 80 characters, and should be as short as possible to convey the essence of the event.
      *
+     * @see #ACTION_DEBUG_EVENT
      * @hide
      */
     @SystemApi
@@ -3181,6 +3203,7 @@
      * the caller does not have adequate permissions for that card.
      */
     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
+    @NonNull
     public List<UiccCardInfo> getUiccCardsInfo() {
         try {
             ITelephony telephony = getITelephony();
@@ -8640,24 +8663,26 @@
 
 
     /**
-     * Returns a well-formed IETF BCP 47 language tag representing the locale from the SIM, e.g,
-     * en-US. Returns {@code null} if no locale could be derived from subscriptions.
+     * Returns a locale based on the country and language from the SIM. Returns {@code null} if
+     * no locale could be derived from subscriptions.
      *
      * <p>Requires Permission:
      * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
      *
      * @see Locale#toLanguageTag()
-     * @see Locale#forLanguageTag(String)
      *
      * @hide
      */
     @SystemApi
     @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
-    @Nullable public String getSimLocale() {
+    @Nullable public Locale getSimLocale() {
         try {
             final ITelephony telephony = getITelephony();
             if (telephony != null) {
-                return telephony.getSimLocaleForSubscriber(getSubId());
+                String languageTag = telephony.getSimLocaleForSubscriber(getSubId());
+                if (!TextUtils.isEmpty(languageTag)) {
+                    return Locale.forLanguageTag(languageTag);
+                }
             }
         } catch (RemoteException ex) {
         }
diff --git a/telephony/java/android/telephony/UiccCardInfo.java b/telephony/java/android/telephony/UiccCardInfo.java
index 19f357a..d95a499 100644
--- a/telephony/java/android/telephony/UiccCardInfo.java
+++ b/telephony/java/android/telephony/UiccCardInfo.java
@@ -15,6 +15,8 @@
  */
 package android.telephony;
 
+import android.annotation.NonNull;
+import android.annotation.Nullable;
 import android.os.Parcel;
 import android.os.Parcelable;
 
@@ -30,6 +32,7 @@
     private final String mEid;
     private final String mIccId;
     private final int mSlotIndex;
+    private final boolean mIsRemovable;
 
     public static final Creator<UiccCardInfo> CREATOR = new Creator<UiccCardInfo>() {
         @Override
@@ -49,6 +52,7 @@
         mEid = in.readString();
         mIccId = in.readString();
         mSlotIndex = in.readInt();
+        mIsRemovable = in.readByte() != 0;
     }
 
     @Override
@@ -58,6 +62,7 @@
         dest.writeString(mEid);
         dest.writeString(mIccId);
         dest.writeInt(mSlotIndex);
+        dest.writeByte((byte) (mIsRemovable ? 1 : 0));
     }
 
     @Override
@@ -65,16 +70,21 @@
         return 0;
     }
 
-    public UiccCardInfo(boolean isEuicc, int cardId, String eid, String iccId, int slotIndex) {
+    /**
+     * @hide
+     */
+    public UiccCardInfo(boolean isEuicc, int cardId, String eid, String iccId, int slotIndex,
+            boolean isRemovable) {
         this.mIsEuicc = isEuicc;
         this.mCardId = cardId;
         this.mEid = eid;
         this.mIccId = iccId;
         this.mSlotIndex = slotIndex;
+        this.mIsRemovable = isRemovable;
     }
 
     /**
-     * Return whether the UiccCardInfo is an eUICC.
+     * Return whether the UICC is an eUICC.
      * @return true if the UICC is an eUICC.
      */
     public boolean isEuicc() {
@@ -96,6 +106,7 @@
      * Note that this field may be omitted if the caller does not have the correct permissions
      * (see {@link TelephonyManager#getUiccCardsInfo()}).
      */
+    @Nullable
     public String getEid() {
         if (!mIsEuicc) {
             return null;
@@ -109,6 +120,7 @@
      * Note that this field may be omitted if the caller does not have the correct permissions
      * (see {@link TelephonyManager#getUiccCardsInfo()}).
      */
+    @Nullable
     public String getIccId() {
         return mIccId;
     }
@@ -121,13 +133,24 @@
     }
 
     /**
-     * Returns a copy of the UiccCardinfo with the clears the EID and ICCID set to null. These
-     * values are generally private and require carrier privileges to view.
+     * Returns a copy of the UiccCardinfo with the EID and ICCID set to null. These values are
+     * generally private and require carrier privileges to view.
      *
      * @hide
      */
+    @NonNull
     public UiccCardInfo getUnprivileged() {
-        return new UiccCardInfo(mIsEuicc, mCardId, null, null, mSlotIndex);
+        return new UiccCardInfo(mIsEuicc, mCardId, null, null, mSlotIndex, mIsRemovable);
+    }
+
+    /**
+     * Return whether the UICC or eUICC is removable.
+     * <p>
+     * UICCs are generally removable, but eUICCs may be removable or built in to the device.
+     * @return true if the UICC or eUICC is removable
+     */
+    public boolean isRemovable() {
+        return mIsRemovable;
     }
 
     @Override
@@ -144,12 +167,13 @@
                 && (mCardId == that.mCardId)
                 && (Objects.equals(mEid, that.mEid))
                 && (Objects.equals(mIccId, that.mIccId))
-                && (mSlotIndex == that.mSlotIndex));
+                && (mSlotIndex == that.mSlotIndex)
+                && (mIsRemovable == that.mIsRemovable));
     }
 
     @Override
     public int hashCode() {
-        return Objects.hash(mIsEuicc, mCardId, mEid, mIccId, mSlotIndex);
+        return Objects.hash(mIsEuicc, mCardId, mEid, mIccId, mSlotIndex, mIsRemovable);
     }
 
     @Override
@@ -164,6 +188,8 @@
                 + mIccId
                 + ", mSlotIndex="
                 + mSlotIndex
+                + ", mIsRemovable="
+                + mIsRemovable
                 + ")";
     }
 }
diff --git a/telephony/java/android/telephony/UiccSlotInfo.java b/telephony/java/android/telephony/UiccSlotInfo.java
index a39992b..93a7da0 100644
--- a/telephony/java/android/telephony/UiccSlotInfo.java
+++ b/telephony/java/android/telephony/UiccSlotInfo.java
@@ -15,15 +15,15 @@
  */
 package android.telephony;
 
+import android.annotation.IntDef;
 import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
+
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.util.Objects;
 
-import android.annotation.IntDef;
-
 /**
  * Class for the information of a UICC slot.
  * @hide
@@ -61,6 +61,7 @@
     private final @CardStateInfo int mCardStateInfo;
     private final int mLogicalSlotIdx;
     private final boolean mIsExtendedApduSupported;
+    private final boolean mIsRemovable;
 
     public static final Creator<UiccSlotInfo> CREATOR = new Creator<UiccSlotInfo>() {
         @Override
@@ -81,6 +82,7 @@
         mCardStateInfo = in.readInt();
         mLogicalSlotIdx = in.readInt();
         mIsExtendedApduSupported = in.readByte() != 0;
+        mIsRemovable = in.readByte() != 0;
     }
 
     @Override
@@ -91,6 +93,7 @@
         dest.writeInt(mCardStateInfo);
         dest.writeInt(mLogicalSlotIdx);
         dest.writeByte((byte) (mIsExtendedApduSupported ? 1 : 0));
+        dest.writeByte((byte) (mIsRemovable ? 1 : 0));
     }
 
     @Override
@@ -98,6 +101,11 @@
         return 0;
     }
 
+    /**
+     * Construct a UiccSlotInfo.
+     * @deprecated apps should not be constructing UiccSlotInfo objects
+     */
+    @Deprecated
     public UiccSlotInfo(boolean isActive, boolean isEuicc, String cardId,
             @CardStateInfo int cardStateInfo, int logicalSlotIdx, boolean isExtendedApduSupported) {
         this.mIsActive = isActive;
@@ -106,6 +114,22 @@
         this.mCardStateInfo = cardStateInfo;
         this.mLogicalSlotIdx = logicalSlotIdx;
         this.mIsExtendedApduSupported = isExtendedApduSupported;
+        this.mIsRemovable = false;
+    }
+
+    /**
+     * @hide
+     */
+    public UiccSlotInfo(boolean isActive, boolean isEuicc, String cardId,
+            @CardStateInfo int cardStateInfo, int logicalSlotIdx, boolean isExtendedApduSupported,
+            boolean isRemovable) {
+        this.mIsActive = isActive;
+        this.mIsEuicc = isEuicc;
+        this.mCardId = cardId;
+        this.mCardStateInfo = cardStateInfo;
+        this.mLogicalSlotIdx = logicalSlotIdx;
+        this.mIsExtendedApduSupported = isExtendedApduSupported;
+        this.mIsRemovable = isRemovable;
     }
 
     public boolean getIsActive() {
@@ -136,6 +160,16 @@
         return mIsExtendedApduSupported;
     }
 
+   /**
+     * Return whether the UICC slot is for a removable UICC.
+     * <p>
+     * UICCs are generally removable, but eUICCs may be removable or built in to the device.
+     * @return true if the slot is for removable UICCs
+     */
+    public boolean isRemovable() {
+        return mIsRemovable;
+    }
+
     @Override
     public boolean equals(Object obj) {
         if (this == obj) {
@@ -151,7 +185,8 @@
                 && (Objects.equals(mCardId, that.mCardId))
                 && (mCardStateInfo == that.mCardStateInfo)
                 && (mLogicalSlotIdx == that.mLogicalSlotIdx)
-                && (mIsExtendedApduSupported == that.mIsExtendedApduSupported);
+                && (mIsExtendedApduSupported == that.mIsExtendedApduSupported)
+                && (mIsRemovable == that.mIsRemovable);
     }
 
     @Override
@@ -163,6 +198,7 @@
         result = 31 * result + mCardStateInfo;
         result = 31 * result + mLogicalSlotIdx;
         result = 31 * result + (mIsExtendedApduSupported ? 1 : 0);
+        result = 31 * result + (mIsRemovable ? 1 : 0);
         return result;
     }
 
@@ -180,6 +216,8 @@
                 + mLogicalSlotIdx
                 + ", mIsExtendedApduSupported="
                 + mIsExtendedApduSupported
+                + ", mIsRemovable="
+                + mIsRemovable
                 + ")";
     }
 }
diff --git a/telephony/java/android/telephony/ims/ImsStreamMediaProfile.java b/telephony/java/android/telephony/ims/ImsStreamMediaProfile.java
index 837ef54..d11a0de 100644
--- a/telephony/java/android/telephony/ims/ImsStreamMediaProfile.java
+++ b/telephony/java/android/telephony/ims/ImsStreamMediaProfile.java
@@ -99,7 +99,7 @@
     public int mRttMode;
     // RTT Audio Speech Indicator
     /** @hide */
-    public boolean mHasRttAudioSpeech = false;
+    public boolean mIsReceivingRttAudio = false;
 
     /** @hide */
     public ImsStreamMediaProfile(Parcel in) {
@@ -201,7 +201,7 @@
                 ", videoQuality=" + mVideoQuality +
                 ", videoDirection=" + mVideoDirection +
                 ", rttMode=" + mRttMode +
-                ", hasRttAudioSpeech=" + mHasRttAudioSpeech + " }";
+                ", hasRttAudioSpeech=" + mIsReceivingRttAudio + " }";
     }
 
     @Override
@@ -216,7 +216,7 @@
         out.writeInt(mVideoQuality);
         out.writeInt(mVideoDirection);
         out.writeInt(mRttMode);
-        out.writeBoolean(mHasRttAudioSpeech);
+        out.writeBoolean(mIsReceivingRttAudio);
     }
 
     private void readFromParcel(Parcel in) {
@@ -225,7 +225,7 @@
         mVideoQuality = in.readInt();
         mVideoDirection = in.readInt();
         mRttMode = in.readInt();
-        mHasRttAudioSpeech = in.readBoolean();
+        mIsReceivingRttAudio = in.readBoolean();
     }
 
     public static final Creator<ImsStreamMediaProfile> CREATOR =
@@ -256,8 +256,12 @@
         mRttMode = rttMode;
     }
 
-    public void setRttAudioSpeech(boolean audioOn) {
-        mHasRttAudioSpeech = audioOn;
+    /**
+     * Sets whether the remote party is transmitting audio over the RTT call.
+     * @param audioOn true if audio is being received, false otherwise.
+     */
+    public void setReceivingRttAudio(boolean audioOn) {
+        mIsReceivingRttAudio = audioOn;
     }
 
     public int getAudioQuality() {
@@ -280,7 +284,10 @@
         return mRttMode;
     }
 
-    public boolean getRttAudioSpeech() {
-        return mHasRttAudioSpeech;
+    /**
+     * @return true if remote party is transmitting audio, false otherwise.
+     */
+    public boolean isReceivingRttAudio() {
+        return mIsReceivingRttAudio;
     }
 }
diff --git a/telephony/java/android/telephony/ims/Rcs1To1Thread.java b/telephony/java/android/telephony/ims/Rcs1To1Thread.java
index d4a78ff..0bb1b43 100644
--- a/telephony/java/android/telephony/ims/Rcs1To1Thread.java
+++ b/telephony/java/android/telephony/ims/Rcs1To1Thread.java
@@ -22,6 +22,8 @@
  * Rcs1To1Thread represents a single RCS conversation thread with a total of two
  * {@link RcsParticipant}s. Please see Section 5 (1-to-1 Messaging) - GSMA RCC.71 (RCS Universal
  * Profile Service Definition Document)
+ *
+ * @hide
  */
 public class Rcs1To1Thread extends RcsThread {
     private int mThreadId;
diff --git a/telephony/java/android/telephony/ims/RcsEvent.java b/telephony/java/android/telephony/ims/RcsEvent.java
index a547c5c0..994b27a 100644
--- a/telephony/java/android/telephony/ims/RcsEvent.java
+++ b/telephony/java/android/telephony/ims/RcsEvent.java
@@ -17,6 +17,8 @@
 
 /**
  * The base class for events that can happen on {@link RcsParticipant}s and {@link RcsThread}s.
+ *
+ * @hide
  */
 public abstract class RcsEvent {
     private final long mTimestamp;
diff --git a/telephony/java/android/telephony/ims/RcsEventQueryParams.java b/telephony/java/android/telephony/ims/RcsEventQueryParams.java
index 9dbfe43..5f8fa80 100644
--- a/telephony/java/android/telephony/ims/RcsEventQueryParams.java
+++ b/telephony/java/android/telephony/ims/RcsEventQueryParams.java
@@ -37,6 +37,8 @@
  * The parameters to pass into
  * {@link RcsMessageStore#getRcsEvents(RcsEventQueryParams)} in order to select a
  * subset of {@link RcsEvent}s present in the message store.
+ *
+ * @hide
  */
 public final class RcsEventQueryParams implements Parcelable {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsEventQueryResult.java b/telephony/java/android/telephony/ims/RcsEventQueryResult.java
index 92bda81..d6347e3 100644
--- a/telephony/java/android/telephony/ims/RcsEventQueryResult.java
+++ b/telephony/java/android/telephony/ims/RcsEventQueryResult.java
@@ -22,6 +22,8 @@
  * The result of a {@link RcsMessageStore#getRcsEvents(RcsEventQueryParams)}
  * call. This class allows getting the token for querying the next batch of events in order to
  * prevent handling large amounts of data at once.
+ *
+ * @hide
  */
 public class RcsEventQueryResult {
     private RcsQueryContinuationToken mContinuationToken;
diff --git a/telephony/java/android/telephony/ims/RcsFileTransferCreationParams.java b/telephony/java/android/telephony/ims/RcsFileTransferCreationParams.java
index 14af8ea..4742ba2 100644
--- a/telephony/java/android/telephony/ims/RcsFileTransferCreationParams.java
+++ b/telephony/java/android/telephony/ims/RcsFileTransferCreationParams.java
@@ -24,6 +24,8 @@
  * Pass an instance of this class to
  * {@link RcsMessage#insertFileTransfer(RcsFileTransferCreationParams)} create an
  * {@link RcsFileTransferPart} and save it into storage.
+ *
+ * @hide
  */
 public final class RcsFileTransferCreationParams implements Parcelable {
     private String mRcsFileTransferSessionId;
diff --git a/telephony/java/android/telephony/ims/RcsFileTransferPart.java b/telephony/java/android/telephony/ims/RcsFileTransferPart.java
index 9531c2e..3816cd4 100644
--- a/telephony/java/android/telephony/ims/RcsFileTransferPart.java
+++ b/telephony/java/android/telephony/ims/RcsFileTransferPart.java
@@ -26,6 +26,8 @@
 /**
  * A part of a composite {@link RcsMessage} that holds a file transfer. Please see Section 7
  * (File Transfer) - GSMA RCC.71 (RCS Universal Profile Service Definition Document)
+ *
+ * @hide
  */
 public class RcsFileTransferPart {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsGroupThread.java b/telephony/java/android/telephony/ims/RcsGroupThread.java
index 6e17bc2..8cd633b 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThread.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThread.java
@@ -29,6 +29,8 @@
  * RcsGroupThread represents a single RCS conversation thread where {@link RcsParticipant}s can join
  * or leave. Please see Section 6 (Group Chat) - GSMA RCC.71 (RCS Universal Profile Service
  * Definition Document)
+ *
+ * @hide
  */
 public class RcsGroupThread extends RcsThread {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadEvent.java b/telephony/java/android/telephony/ims/RcsGroupThreadEvent.java
index 99086aa..4a6b963 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadEvent.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadEvent.java
@@ -19,6 +19,8 @@
 
 /**
  * An event that happened on an {@link RcsGroupThread}.
+ *
+ * @hide
  */
 public abstract class RcsGroupThreadEvent extends RcsEvent {
     private final int mRcsGroupThreadId;
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEvent.java b/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEvent.java
index cbd762d..3c6c74f 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEvent.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEvent.java
@@ -22,6 +22,8 @@
 /**
  * An event that indicates an {@link RcsGroupThread}'s icon was changed. Please see R6-2-5 - GSMA
  * RCC.71 (RCS Universal Profile Service Definition Document)
+ *
+ * @hide
  */
 public final class RcsGroupThreadIconChangedEvent extends RcsGroupThreadEvent {
     private final Uri mNewIcon;
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEvent.java b/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEvent.java
index a2a4fab..5403253 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEvent.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEvent.java
@@ -21,6 +21,8 @@
 /**
  * An event that indicates an {@link RcsGroupThread}'s name was changed. Please see R6-2-5 - GSMA
  * RCC.71 (RCS Universal Profile Service Definition Document)
+ *
+ * @hide
  */
 public final class RcsGroupThreadNameChangedEvent extends RcsGroupThreadEvent {
     private final String mNewName;
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEvent.java b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEvent.java
index 183cd9a..48be479 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEvent.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEvent.java
@@ -20,6 +20,8 @@
 /**
  * An event that indicates an RCS participant has joined an {@link RcsThread}. Please see US6-3 -
  * GSMA RCC.71 (RCS Universal Profile Service Definition Document)
+ *
+ * @hide
  */
 public final class RcsGroupThreadParticipantJoinedEvent extends RcsGroupThreadEvent {
     private final RcsParticipant mJoinedParticipantId;
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEvent.java b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEvent.java
index c12549b..b724a3f 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEvent.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEvent.java
@@ -20,6 +20,8 @@
 /**
  * An event that indicates an RCS participant has left an {@link RcsThread}. Please see US6-23 -
  * GSMA RCC.71 (RCS Universal Profile Service Definition Document)
+ *
+ * @hide
  */
 public final class RcsGroupThreadParticipantLeftEvent extends RcsGroupThreadEvent {
     private RcsParticipant mLeavingParticipant;
diff --git a/telephony/java/android/telephony/ims/RcsIncomingMessage.java b/telephony/java/android/telephony/ims/RcsIncomingMessage.java
index 61911ab..06e2a41 100644
--- a/telephony/java/android/telephony/ims/RcsIncomingMessage.java
+++ b/telephony/java/android/telephony/ims/RcsIncomingMessage.java
@@ -19,6 +19,8 @@
 
 /**
  * This is a single instance of a message received over RCS.
+ *
+ * @hide
  */
 public class RcsIncomingMessage extends RcsMessage {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsIncomingMessageCreationParams.java b/telephony/java/android/telephony/ims/RcsIncomingMessageCreationParams.java
index 61dedbc..58dc1bc 100644
--- a/telephony/java/android/telephony/ims/RcsIncomingMessageCreationParams.java
+++ b/telephony/java/android/telephony/ims/RcsIncomingMessageCreationParams.java
@@ -24,6 +24,8 @@
  * {@link RcsIncomingMessageCreationParams} is a collection of parameters that should be passed
  * into {@link RcsThread#addIncomingMessage(RcsIncomingMessageCreationParams)} to generate an
  * {@link RcsIncomingMessage} on that {@link RcsThread}
+ *
+ * @hide
  */
 public final class RcsIncomingMessageCreationParams extends RcsMessageCreationParams implements
         Parcelable {
diff --git a/telephony/java/android/telephony/ims/RcsManager.java b/telephony/java/android/telephony/ims/RcsManager.java
index 22e4b22..63dc1ac 100644
--- a/telephony/java/android/telephony/ims/RcsManager.java
+++ b/telephony/java/android/telephony/ims/RcsManager.java
@@ -20,6 +20,8 @@
 
 /**
  * The manager class for RCS related utilities.
+ *
+ * @hide
  */
 @SystemService(Context.TELEPHONY_RCS_SERVICE)
 public class RcsManager {
diff --git a/telephony/java/android/telephony/ims/RcsMessage.java b/telephony/java/android/telephony/ims/RcsMessage.java
index 3227413..b0d0d5a 100644
--- a/telephony/java/android/telephony/ims/RcsMessage.java
+++ b/telephony/java/android/telephony/ims/RcsMessage.java
@@ -27,6 +27,8 @@
 
 /**
  * This is a single instance of a message sent or received over RCS.
+ *
+ * @hide
  */
 public abstract class RcsMessage {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsMessageCreationParams.java b/telephony/java/android/telephony/ims/RcsMessageCreationParams.java
index c46c605..f0eea88 100644
--- a/telephony/java/android/telephony/ims/RcsMessageCreationParams.java
+++ b/telephony/java/android/telephony/ims/RcsMessageCreationParams.java
@@ -27,6 +27,8 @@
  * {@link RcsThread#addIncomingMessage(RcsIncomingMessageCreationParams)} and
  * {@link RcsThread#addOutgoingMessage(RcsOutgoingMessageCreationParams)} to create and persist
  * {@link RcsMessage}s on an {@link RcsThread}
+ *
+ * @hide
  */
 public class RcsMessageCreationParams {
     // The globally unique id of the RcsMessage to be created.
diff --git a/telephony/java/android/telephony/ims/RcsMessageQueryParams.java b/telephony/java/android/telephony/ims/RcsMessageQueryParams.java
index 535a597..6491ac9 100644
--- a/telephony/java/android/telephony/ims/RcsMessageQueryParams.java
+++ b/telephony/java/android/telephony/ims/RcsMessageQueryParams.java
@@ -31,6 +31,8 @@
  * The parameters to pass into
  * {@link RcsMessageStore#getRcsMessages(RcsMessageQueryParams)} in order to select a
  * subset of {@link RcsMessage}s present in the message store.
+ *
+ * @hide
  */
 public final class RcsMessageQueryParams implements Parcelable {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsMessageQueryResult.java b/telephony/java/android/telephony/ims/RcsMessageQueryResult.java
index 3514b48..e4020c1 100644
--- a/telephony/java/android/telephony/ims/RcsMessageQueryResult.java
+++ b/telephony/java/android/telephony/ims/RcsMessageQueryResult.java
@@ -32,6 +32,8 @@
  * The result of a {@link RcsMessageStore#getRcsMessages(RcsMessageQueryParams)}
  * call. This class allows getting the token for querying the next batch of messages in order to
  * prevent handling large amounts of data at once.
+ *
+ * @hide
  */
 public final class RcsMessageQueryResult implements Parcelable {
     // The token to continue the query to get the next batch of results
diff --git a/telephony/java/android/telephony/ims/RcsMessageSnippet.java b/telephony/java/android/telephony/ims/RcsMessageSnippet.java
index b0b930c..9064251 100644
--- a/telephony/java/android/telephony/ims/RcsMessageSnippet.java
+++ b/telephony/java/android/telephony/ims/RcsMessageSnippet.java
@@ -23,6 +23,8 @@
 
 /**
  * An immutable summary of the latest {@link RcsMessage} on an {@link RcsThread}
+ *
+ * @hide
  */
 public final class RcsMessageSnippet implements Parcelable {
     private final String mText;
diff --git a/telephony/java/android/telephony/ims/RcsMessageStore.java b/telephony/java/android/telephony/ims/RcsMessageStore.java
index 31f2983..3111652 100644
--- a/telephony/java/android/telephony/ims/RcsMessageStore.java
+++ b/telephony/java/android/telephony/ims/RcsMessageStore.java
@@ -26,6 +26,8 @@
 /**
  * RcsMessageStore is the application interface to RcsProvider and provides access methods to
  * RCS related database tables.
+ *
+ * @hide
  */
 public class RcsMessageStore {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsMessageStoreException.java b/telephony/java/android/telephony/ims/RcsMessageStoreException.java
index f25bb17..3b3fcf2 100644
--- a/telephony/java/android/telephony/ims/RcsMessageStoreException.java
+++ b/telephony/java/android/telephony/ims/RcsMessageStoreException.java
@@ -19,6 +19,8 @@
 /**
  * An exception that happened on {@link RcsMessageStore} or one of the derived storage classes in
  * {@link android.telephony.ims}
+ *
+ * @hide
  */
 public class RcsMessageStoreException extends Exception {
 
diff --git a/telephony/java/android/telephony/ims/RcsOutgoingMessage.java b/telephony/java/android/telephony/ims/RcsOutgoingMessage.java
index 06fb832..1b4bfe5 100644
--- a/telephony/java/android/telephony/ims/RcsOutgoingMessage.java
+++ b/telephony/java/android/telephony/ims/RcsOutgoingMessage.java
@@ -23,6 +23,8 @@
 
 /**
  * This is a single instance of a message sent over RCS.
+ *
+ * @hide
  */
 public class RcsOutgoingMessage extends RcsMessage {
     RcsOutgoingMessage(int id) {
diff --git a/telephony/java/android/telephony/ims/RcsOutgoingMessageCreationParams.java b/telephony/java/android/telephony/ims/RcsOutgoingMessageCreationParams.java
index 979634a..81e3244 100644
--- a/telephony/java/android/telephony/ims/RcsOutgoingMessageCreationParams.java
+++ b/telephony/java/android/telephony/ims/RcsOutgoingMessageCreationParams.java
@@ -23,6 +23,8 @@
  * {@link RcsOutgoingMessageCreationParams} is a collection of parameters that should be passed
  * into {@link RcsThread#addOutgoingMessage(RcsOutgoingMessageCreationParams)} to generate an
  * {@link RcsOutgoingMessage} on that {@link RcsThread}
+ *
+ * @hide
  */
 public final class RcsOutgoingMessageCreationParams extends RcsMessageCreationParams
         implements Parcelable {
diff --git a/telephony/java/android/telephony/ims/RcsOutgoingMessageDelivery.java b/telephony/java/android/telephony/ims/RcsOutgoingMessageDelivery.java
index 1c87b13..2db49c6 100644
--- a/telephony/java/android/telephony/ims/RcsOutgoingMessageDelivery.java
+++ b/telephony/java/android/telephony/ims/RcsOutgoingMessageDelivery.java
@@ -21,6 +21,8 @@
 /**
  * This class holds the delivery information of an {@link RcsOutgoingMessage} for each
  * {@link RcsParticipant} that the message was intended for.
+ *
+ * @hide
  */
 public class RcsOutgoingMessageDelivery {
     // The participant that this delivery is intended for
diff --git a/telephony/java/android/telephony/ims/RcsParticipant.java b/telephony/java/android/telephony/ims/RcsParticipant.java
index 7ba5d8e..bcf134a 100644
--- a/telephony/java/android/telephony/ims/RcsParticipant.java
+++ b/telephony/java/android/telephony/ims/RcsParticipant.java
@@ -20,6 +20,8 @@
 
 /**
  * RcsParticipant is an RCS capable contact that can participate in {@link RcsThread}s.
+ *
+ * @hide
  */
 public class RcsParticipant {
     // The row ID of this participant in the database
diff --git a/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEvent.java b/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEvent.java
index cc2613f..61801f3 100644
--- a/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEvent.java
+++ b/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEvent.java
@@ -21,6 +21,8 @@
 /**
  * An event that indicates an {@link RcsParticipant}'s alias was changed. Please see US18-2 - GSMA
  * RCC.71 (RCS Universal Profile Service Definition Document)
+ *
+ * @hide
  */
 public final class RcsParticipantAliasChangedEvent extends RcsEvent {
     // The participant that changed their alias
diff --git a/telephony/java/android/telephony/ims/RcsParticipantQueryParams.java b/telephony/java/android/telephony/ims/RcsParticipantQueryParams.java
index d24d079..ada9b8a 100644
--- a/telephony/java/android/telephony/ims/RcsParticipantQueryParams.java
+++ b/telephony/java/android/telephony/ims/RcsParticipantQueryParams.java
@@ -30,6 +30,8 @@
  * The parameters to pass into
  * {@link RcsMessageStore#getRcsParticipants(RcsParticipantQueryParams)} in order to select a
  * subset of {@link RcsThread}s present in the message store.
+ *
+ * @hide
  */
 public final class RcsParticipantQueryParams implements Parcelable {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsParticipantQueryResult.java b/telephony/java/android/telephony/ims/RcsParticipantQueryResult.java
index 505f1a5..92e2fa78 100644
--- a/telephony/java/android/telephony/ims/RcsParticipantQueryResult.java
+++ b/telephony/java/android/telephony/ims/RcsParticipantQueryResult.java
@@ -28,6 +28,8 @@
  * The result of a {@link RcsMessageStore#getRcsParticipants(RcsParticipantQueryParams)}
  * call. This class allows getting the token for querying the next batch of participants in order to
  * prevent handling large amounts of data at once.
+ *
+ * @hide
  */
 public final class RcsParticipantQueryResult implements Parcelable {
     // A token for the caller to continue their query for the next batch of results
diff --git a/telephony/java/android/telephony/ims/RcsQueryContinuationToken.java b/telephony/java/android/telephony/ims/RcsQueryContinuationToken.java
index 08643de..970c110 100644
--- a/telephony/java/android/telephony/ims/RcsQueryContinuationToken.java
+++ b/telephony/java/android/telephony/ims/RcsQueryContinuationToken.java
@@ -31,6 +31,8 @@
  * @see RcsMessageQueryResult#getContinuationToken()
  * @see RcsParticipantQueryResult#getContinuationToken()
  * @see RcsThreadQueryResult#getContinuationToken()
+ *
+ * @hide
  */
 public final class RcsQueryContinuationToken implements Parcelable {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsThread.java b/telephony/java/android/telephony/ims/RcsThread.java
index e015dd3..cf1dc76 100644
--- a/telephony/java/android/telephony/ims/RcsThread.java
+++ b/telephony/java/android/telephony/ims/RcsThread.java
@@ -27,6 +27,8 @@
 /**
  * RcsThread represents a single RCS conversation thread. It holds messages that were sent and
  * received and events that occurred on that thread.
+ *
+ * @hide
  */
 public abstract class RcsThread {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsThreadQueryParams.java b/telephony/java/android/telephony/ims/RcsThreadQueryParams.java
index 05a5a39..81eee40 100644
--- a/telephony/java/android/telephony/ims/RcsThreadQueryParams.java
+++ b/telephony/java/android/telephony/ims/RcsThreadQueryParams.java
@@ -35,6 +35,8 @@
 /**
  * The parameters to pass into {@link RcsMessageStore#getRcsThreads(RcsThreadQueryParams)} in
  * order to select a subset of {@link RcsThread}s present in the message store.
+ *
+ * @hide
  */
 public final class RcsThreadQueryParams implements Parcelable {
     /**
diff --git a/telephony/java/android/telephony/ims/RcsThreadQueryResult.java b/telephony/java/android/telephony/ims/RcsThreadQueryResult.java
index 1cac61d..9f2fba5 100644
--- a/telephony/java/android/telephony/ims/RcsThreadQueryResult.java
+++ b/telephony/java/android/telephony/ims/RcsThreadQueryResult.java
@@ -32,6 +32,8 @@
  * The result of a {@link RcsMessageStore#getRcsThreads(RcsThreadQueryParams)}
  * call. This class allows getting the token for querying the next batch of threads in order to
  * prevent handling large amounts of data at once.
+ *
+ * @hide
  */
 public final class RcsThreadQueryResult implements Parcelable {
     // A token for the caller to continue their query for the next batch of results
diff --git a/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl b/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
index e9eba32..5719124 100644
--- a/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
@@ -84,6 +84,6 @@
     void notifyPreferredDataSubIdChanged(int preferredSubId);
     void notifyRadioPowerStateChanged(in int state);
     void notifyEmergencyNumberList();
-    void notifyCallQualityChanged(in CallQuality callQuality, int phoneId);
+    void notifyCallQualityChanged(in CallQuality callQuality, int phoneId, int callNetworkType);
     void notifyImsDisconnectCause(int subId, in ImsReasonInfo imsReasonInfo);
 }
diff --git a/test-base/Android.bp b/test-base/Android.bp
index 157609c..8aa0aaf 100644
--- a/test-base/Android.bp
+++ b/test-base/Android.bp
@@ -44,7 +44,7 @@
 // ==========================================
 // This is only intended for inclusion in the android.test.runner-minus-junit,
 // robolectric_android-all-stub and repackaged.android.test.* libraries.
-// Must not be used elewhere.
+// Must not be used elsewhere.
 java_library_static {
     name: "android.test.base_static",
     installable: false,
@@ -61,19 +61,6 @@
     sdk_version: "current",
 }
 
-// Build the legacy-test library
-// =============================
-// This contains the junit.framework and android.test classes that were in
-// Android API level 25 excluding those from android.test.runner.
-// Also contains the com.android.internal.util.Predicate[s] classes.
-java_library {
-    name: "legacy-test",
-    installable: true,
-
-    sdk_version: "current",
-    static_libs: ["android.test.base_static"],
-}
-
 // Build the repackaged.android.test.base library
 // ==============================================
 // This contains repackaged versions of the classes from
@@ -93,8 +80,8 @@
 // ===============================================
 // This contains the android.test classes from android.test.base plus
 // the com.android.internal.util.Predicate[s] classes. This is only
-// intended for inclusion in the android.test.legacy and
-// legacy-android-test static libraries and must not be used elsewhere.
+// intended for inclusion in android.test.legacy and must not be used
+// elsewhere.
 java_library_static {
     name: "android.test.base-minus-junit",
 
diff --git a/test-legacy/Android.bp b/test-legacy/Android.bp
deleted file mode 100644
index a69f422..0000000
--- a/test-legacy/Android.bp
+++ /dev/null
@@ -1,36 +0,0 @@
-//
-// Copyright (C) 2018 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-// Build the legacy-android-test library
-// =====================================
-// This contains the android.test classes that were in Android API level 25,
-// including those from android.test.runner.
-// Also contains the com.android.internal.util.Predicate[s] classes.
-java_library_static {
-    name: "legacy-android-test",
-
-    static_libs: [
-        "android.test.base-minus-junit",
-        "android.test.runner-minus-junit",
-        "android.test.mock_static",
-    ],
-
-    no_framework_libs: true,
-    libs: [
-        "framework",
-        "junit",
-    ],
-}
diff --git a/test-legacy/Android.mk b/test-legacy/Android.mk
index da47de0..af26c5b 100644
--- a/test-legacy/Android.mk
+++ b/test-legacy/Android.mk
@@ -24,35 +24,16 @@
 # Built against the SDK so that it can be statically included in APKs
 # without breaking link type checks.
 #
-# This builds directly from the source rather than simply statically
-# including the android.test.base-minus-junit and
-# android.test.runner-minus-junit libraries because the latter library
-# cannot itself be built against the SDK. That is because it uses on
-# an internal method (setTestContext) on the AndroidTestCase class.
-# That class is provided by both the android.test.base-minus-junit and
-# the current SDK and as the latter is first on the classpath its
-# version is used. Unfortunately, it does not provide the internal
-# method and so compilation fails.
-#
-# Building from source avoids that because the compiler will use the
-# source version of AndroidTestCase instead of the one from the current
-# SDK.
-#
-# The use of the internal method does not prevent this from being
-# statically included because the class that provides the method is
-# also included in this library.
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := android.test.legacy
 
-LOCAL_SRC_FILES := \
-    $(call all-java-files-under, ../test-base/src/android) \
-    $(call all-java-files-under, ../test-base/src/com) \
-    $(call all-java-files-under, ../test-runner/src/android) \
-
 LOCAL_SDK_VERSION := current
 
 LOCAL_JAVA_LIBRARIES := junit android.test.mock.stubs
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    android.test.base-minus-junit \
+    android.test.runner-minus-junit \
 
 include $(BUILD_STATIC_JAVA_LIBRARY)
 
diff --git a/test-mock/Android.bp b/test-mock/Android.bp
index 43b765d..e1d6e01 100644
--- a/test-mock/Android.bp
+++ b/test-mock/Android.bp
@@ -30,19 +30,3 @@
     srcs_lib_whitelist_pkgs: ["android"],
     compile_dex: true,
 }
-
-// Build the android.test.mock_static library
-// ==========================================
-// This is only intended for inclusion in the legacy-android-test.
-// Must not be used elewhere.
-java_library_static {
-    name: "android.test.mock_static",
-
-    java_version: "1.8",
-    srcs: ["src/**/*.java"],
-
-    no_framework_libs: true,
-    libs: [
-        "framework",
-    ],
-}
diff --git a/test-runner/Android.bp b/test-runner/Android.bp
index db5053e..3521202 100644
--- a/test-runner/Android.bp
+++ b/test-runner/Android.bp
@@ -45,7 +45,7 @@
 
 // Build the android.test.runner-minus-junit library
 // =================================================
-// This is only intended for inclusion in the legacy-android-test static
+// This is only intended for inclusion in the android.test.legacy static
 // library and must not be used elsewhere.
 java_library {
     name: "android.test.runner-minus-junit",
diff --git a/tests/net/java/com/android/server/ConnectivityServiceTest.java b/tests/net/java/com/android/server/ConnectivityServiceTest.java
index d1a0692..c126026 100644
--- a/tests/net/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/net/java/com/android/server/ConnectivityServiceTest.java
@@ -17,10 +17,10 @@
 package com.android.server;
 
 import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
+import static android.net.ConnectivityManager.NETID_UNSET;
 import static android.net.ConnectivityManager.PRIVATE_DNS_MODE_OFF;
 import static android.net.ConnectivityManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
 import static android.net.ConnectivityManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME;
-import static android.net.ConnectivityManager.NETID_UNSET;
 import static android.net.ConnectivityManager.TYPE_ETHERNET;
 import static android.net.ConnectivityManager.TYPE_MOBILE;
 import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
@@ -1798,6 +1798,12 @@
                     fn.test((NetworkCapabilities) cbi.arg));
         }
 
+        void expectLinkPropertiesLike(Predicate<LinkProperties> fn, MockNetworkAgent agent) {
+            CallbackInfo cbi = expectCallback(CallbackState.LINK_PROPERTIES, agent);
+            assertTrue("Received LinkProperties don't match expectations : " + cbi.arg,
+                    fn.test((LinkProperties) cbi.arg));
+        }
+
         void expectBlockedStatusCallback(boolean expectBlocked, MockNetworkAgent agent) {
             CallbackInfo cbi = expectCallback(CallbackState.BLOCKED_STATUS, agent);
             boolean actualBlocked = (boolean) cbi.arg;
@@ -5087,6 +5093,9 @@
     public void testStackedLinkProperties() throws UnknownHostException, RemoteException {
         final LinkAddress myIpv4 = new LinkAddress("1.2.3.4/24");
         final LinkAddress myIpv6 = new LinkAddress("2001:db8:1::1/64");
+        final String kNat64PrefixString = "2001:db8:64:64:64:64::";
+        final IpPrefix kNat64Prefix = new IpPrefix(InetAddress.getByName(kNat64PrefixString), 96);
+
         final NetworkRequest networkRequest = new NetworkRequest.Builder()
                 .addTransportType(TRANSPORT_CELLULAR)
                 .addCapability(NET_CAPABILITY_INTERNET)
@@ -5094,8 +5103,9 @@
         final TestNetworkCallback networkCallback = new TestNetworkCallback();
         mCm.registerNetworkCallback(networkRequest, networkCallback);
 
-        // Prepare ipv6 only link properties and connect.
+        // Prepare ipv6 only link properties.
         mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
+        final int cellNetId = mCellNetworkAgent.getNetwork().netId;
         final LinkProperties cellLp = new LinkProperties();
         cellLp.setInterfaceName(MOBILE_IFNAME);
         cellLp.addLinkAddress(myIpv6);
@@ -5105,15 +5115,44 @@
         when(mNetworkManagementService.getInterfaceConfig(CLAT_PREFIX + MOBILE_IFNAME))
                 .thenReturn(getClatInterfaceConfig(myIpv4));
 
-        // Connect with ipv6 link properties, then expect clat setup ipv4 and update link
-        // properties properly.
+        // Connect with ipv6 link properties. Expect prefix discovery to be started.
         mCellNetworkAgent.sendLinkProperties(cellLp);
         mCellNetworkAgent.connect(true);
         networkCallback.expectAvailableThenValidatedCallbacks(mCellNetworkAgent);
-        verify(mMockNetd, times(1)).clatdStart(MOBILE_IFNAME);
-        Nat464Xlat clat = mService.getNat464Xlat(mCellNetworkAgent);
+        verify(mMockNetd, times(1)).resolverStartPrefix64Discovery(cellNetId);
 
-        // Clat iface up, expect stack link updated.
+        // Switching default network updates TCP buffer sizes.
+        verifyTcpBufferSizeChange(ConnectivityService.DEFAULT_TCP_BUFFER_SIZES);
+
+        // Add an IPv4 address. Expect prefix discovery to be stopped. Netd doesn't tell us that
+        // the NAT64 prefix was removed because one was never discovered.
+        cellLp.addLinkAddress(myIpv4);
+        mCellNetworkAgent.sendLinkProperties(cellLp);
+        networkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
+        verify(mMockNetd, times(1)).resolverStopPrefix64Discovery(cellNetId);
+
+        verifyNoMoreInteractions(mMockNetd);
+        reset(mMockNetd);
+
+        // Remove IPv4 address. Expect prefix discovery to be started again.
+        cellLp.removeLinkAddress(myIpv4);
+        cellLp.removeRoute(new RouteInfo(myIpv4, null, MOBILE_IFNAME));
+        mCellNetworkAgent.sendLinkProperties(cellLp);
+        networkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
+        verify(mMockNetd, times(1)).resolverStartPrefix64Discovery(cellNetId);
+
+        // When NAT64 prefix discovery succeeds, LinkProperties are updated and clatd is started.
+        Nat464Xlat clat = mService.getNat464Xlat(mCellNetworkAgent);
+        assertNull(mCm.getLinkProperties(mCellNetworkAgent.getNetwork()).getNat64Prefix());
+        mService.mNetdEventCallback.onNat64PrefixEvent(cellNetId, true /* added */,
+                kNat64PrefixString, 96);
+        LinkProperties lpBeforeClat = (LinkProperties) networkCallback.expectCallback(
+                CallbackState.LINK_PROPERTIES, mCellNetworkAgent).arg;
+        assertEquals(0, lpBeforeClat.getStackedLinks().size());
+        assertEquals(kNat64Prefix, lpBeforeClat.getNat64Prefix());
+        verify(mMockNetd, times(1)).clatdStart(MOBILE_IFNAME, kNat64Prefix.toString());
+
+        // Clat iface comes up. Expect stacked link to be added.
         clat.interfaceLinkStateChanged(CLAT_PREFIX + MOBILE_IFNAME, true);
         networkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
         List<LinkProperties> stackedLps = mCm.getLinkProperties(mCellNetworkAgent.getNetwork())
@@ -5130,20 +5169,66 @@
         assertNotEquals(stackedLpsAfterChange, Collections.EMPTY_LIST);
         assertEquals(makeClatLinkProperties(myIpv4), stackedLpsAfterChange.get(0));
 
-        // Add ipv4 address, expect stacked linkproperties be cleaned up
+        // Add ipv4 address, expect that clatd and prefix discovery are stopped and stacked
+        // linkproperties are cleaned up.
         cellLp.addLinkAddress(myIpv4);
         cellLp.addRoute(new RouteInfo(myIpv4, null, MOBILE_IFNAME));
         mCellNetworkAgent.sendLinkProperties(cellLp);
         networkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
         verify(mMockNetd, times(1)).clatdStop(MOBILE_IFNAME);
+        verify(mMockNetd, times(1)).resolverStopPrefix64Discovery(cellNetId);
 
-        // Clat iface removed, expect linkproperties revert to original one
-        clat.interfaceRemoved(CLAT_PREFIX + MOBILE_IFNAME);
+        // As soon as stop is called, the linkproperties lose the stacked interface.
         networkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
         LinkProperties actualLpAfterIpv4 = mCm.getLinkProperties(mCellNetworkAgent.getNetwork());
-        assertEquals(cellLp, actualLpAfterIpv4);
+        LinkProperties expected = new LinkProperties(cellLp);
+        expected.setNat64Prefix(kNat64Prefix);
+        assertEquals(expected, actualLpAfterIpv4);
+        assertEquals(0, actualLpAfterIpv4.getStackedLinks().size());
 
-        // Clean up
+        // The interface removed callback happens but has no effect after stop is called.
+        clat.interfaceRemoved(CLAT_PREFIX + MOBILE_IFNAME);
+        networkCallback.assertNoCallback();
+
+        verifyNoMoreInteractions(mMockNetd);
+        reset(mMockNetd);
+
+        // Stopping prefix discovery causes netd to tell us that the NAT64 prefix is gone.
+        mService.mNetdEventCallback.onNat64PrefixEvent(cellNetId, false /* added */,
+                kNat64PrefixString, 96);
+        networkCallback.expectLinkPropertiesLike((lp) -> lp.getNat64Prefix() == null,
+                mCellNetworkAgent);
+
+        // Remove IPv4 address and expect prefix discovery and clatd to be started again.
+        cellLp.removeLinkAddress(myIpv4);
+        cellLp.removeRoute(new RouteInfo(myIpv4, null, MOBILE_IFNAME));
+        cellLp.removeDnsServer(InetAddress.getByName("8.8.8.8"));
+        mCellNetworkAgent.sendLinkProperties(cellLp);
+        networkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
+        verify(mMockNetd, times(1)).resolverStartPrefix64Discovery(cellNetId);
+        mService.mNetdEventCallback.onNat64PrefixEvent(cellNetId, true /* added */,
+                kNat64PrefixString, 96);
+        networkCallback.expectCallback(CallbackState.LINK_PROPERTIES, mCellNetworkAgent);
+        verify(mMockNetd, times(1)).clatdStart(MOBILE_IFNAME, kNat64Prefix.toString());
+
+
+        // Clat iface comes up. Expect stacked link to be added.
+        clat.interfaceLinkStateChanged(CLAT_PREFIX + MOBILE_IFNAME, true);
+        networkCallback.expectLinkPropertiesLike(
+                (lp) -> lp.getStackedLinks().size() == 1 && lp.getNat64Prefix() != null,
+                mCellNetworkAgent);
+
+        // NAT64 prefix is removed. Expect that clat is stopped.
+        mService.mNetdEventCallback.onNat64PrefixEvent(cellNetId, false /* added */,
+                kNat64PrefixString, 96);
+        networkCallback.expectLinkPropertiesLike(
+                (lp) -> lp.getStackedLinks().size() == 0 && lp.getNat64Prefix() == null,
+                mCellNetworkAgent);
+        verify(mMockNetd, times(1)).clatdStop(MOBILE_IFNAME);
+        networkCallback.expectLinkPropertiesLike((lp) -> lp.getStackedLinks().size() == 0,
+                mCellNetworkAgent);
+
+        // Clean up.
         mCellNetworkAgent.disconnect();
         networkCallback.expectCallback(CallbackState.LOST, mCellNetworkAgent);
         networkCallback.assertNoCallback();
@@ -5224,30 +5309,34 @@
         mCm.unregisterNetworkCallback(networkCallback);
     }
 
-    private static final String TEST_TCP_BUFFER_SIZES = "1,2,3,4,5,6";
-
-    private void verifyTcpBufferSizeChange(String tcpBufferSizes) throws Exception {
+    private void verifyTcpBufferSizeChange(String tcpBufferSizes) {
         String[] values = tcpBufferSizes.split(",");
         String rmemValues = String.join(" ", values[0], values[1], values[2]);
         String wmemValues = String.join(" ", values[3], values[4], values[5]);
         waitForIdle();
-        verify(mMockNetd, atLeastOnce()).setTcpRWmemorySize(rmemValues, wmemValues);
+        try {
+            verify(mMockNetd, atLeastOnce()).setTcpRWmemorySize(rmemValues, wmemValues);
+        } catch (RemoteException e) {
+            fail("mMockNetd should never throw RemoteException");
+        }
         reset(mMockNetd);
     }
 
     @Test
-    public void testTcpBufferReset() throws Exception {
+    public void testTcpBufferReset() {
+        final String testTcpBufferSizes = "1,2,3,4,5,6";
+
         mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
         reset(mMockNetd);
-        // Simple connection should have updated tcp buffer size.
+        // Switching default network updates TCP buffer sizes.
         mCellNetworkAgent.connect(false);
         verifyTcpBufferSizeChange(ConnectivityService.DEFAULT_TCP_BUFFER_SIZES);
 
         // Change link Properties should have updated tcp buffer size.
         LinkProperties lp = new LinkProperties();
-        lp.setTcpBufferSizes(TEST_TCP_BUFFER_SIZES);
+        lp.setTcpBufferSizes(testTcpBufferSizes);
         mCellNetworkAgent.sendLinkProperties(lp);
-        verifyTcpBufferSizeChange(TEST_TCP_BUFFER_SIZES);
+        verifyTcpBufferSizeChange(testTcpBufferSizes);
     }
 
     @Test
diff --git a/tests/net/java/com/android/server/connectivity/Nat464XlatTest.java b/tests/net/java/com/android/server/connectivity/Nat464XlatTest.java
index 07b1d05..37c0df8 100644
--- a/tests/net/java/com/android/server/connectivity/Nat464XlatTest.java
+++ b/tests/net/java/com/android/server/connectivity/Nat464XlatTest.java
@@ -16,9 +16,11 @@
 
 package com.android.server.connectivity;
 
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.inOrder;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyNoMoreInteractions;
@@ -27,6 +29,7 @@
 import android.net.ConnectivityManager;
 import android.net.INetd;
 import android.net.InterfaceConfiguration;
+import android.net.IpPrefix;
 import android.net.LinkAddress;
 import android.net.LinkProperties;
 import android.net.NetworkInfo;
@@ -43,6 +46,7 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.ArgumentCaptor;
+import org.mockito.InOrder;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
@@ -53,6 +57,8 @@
     static final String BASE_IFACE = "test0";
     static final String STACKED_IFACE = "v4-test0";
     static final LinkAddress ADDR = new LinkAddress("192.0.2.5/29");
+    static final String NAT64_PREFIX = "64:ff9b::/96";
+    static final int NETID = 42;
 
     @Mock ConnectivityService mConnectivity;
     @Mock NetworkMisc mMisc;
@@ -65,7 +71,11 @@
     Handler mHandler;
 
     Nat464Xlat makeNat464Xlat() {
-        return new Nat464Xlat(mNai, mNetd, mNms);
+        return new Nat464Xlat(mNai, mNetd, mNms) {
+            @Override protected int getNetId() {
+                return NETID;
+            }
+        };
     }
 
     @Before
@@ -87,6 +97,24 @@
         when(mConfig.getLinkAddress()).thenReturn(ADDR);
     }
 
+    private void assertRequiresClat(boolean expected, NetworkAgentInfo nai) {
+        String msg = String.format("requiresClat expected %b for type=%d state=%s skip=%b "
+                + "nat64Prefix=%s addresses=%s", expected, nai.networkInfo.getType(),
+                nai.networkInfo.getDetailedState(),
+                mMisc.skip464xlat, nai.linkProperties.getNat64Prefix(),
+                nai.linkProperties.getLinkAddresses());
+        assertEquals(msg, expected, Nat464Xlat.requiresClat(nai));
+    }
+
+    private void assertShouldStartClat(boolean expected, NetworkAgentInfo nai) {
+        String msg = String.format("shouldStartClat expected %b for type=%d state=%s skip=%b "
+                + "nat64Prefix=%s addresses=%s", expected, nai.networkInfo.getType(),
+                nai.networkInfo.getDetailedState(),
+                mMisc.skip464xlat, nai.linkProperties.getNat64Prefix(),
+                nai.linkProperties.getLinkAddresses());
+        assertEquals(msg, expected, Nat464Xlat.shouldStartClat(nai));
+    }
+
     @Test
     public void testRequiresClat() throws Exception {
         final int[] supportedTypes = {
@@ -102,20 +130,45 @@
             NetworkInfo.DetailedState.SUSPENDED,
         };
 
+        LinkProperties oldLp = new LinkProperties(mNai.linkProperties);
         for (int type : supportedTypes) {
             mNai.networkInfo.setType(type);
             for (NetworkInfo.DetailedState state : supportedDetailedStates) {
                 mNai.networkInfo.setDetailedState(state, "reason", "extraInfo");
-                String msg = String.format("requiresClat expected for type=%d state=%s",
-                        type, state);
+
+                mNai.linkProperties.setNat64Prefix(new IpPrefix("2001:db8:0:64::/96"));
+                assertRequiresClat(false, mNai);
+                assertShouldStartClat(false, mNai);
+
+                mNai.linkProperties.addLinkAddress(new LinkAddress("fc00::1/64"));
+                assertRequiresClat(false, mNai);
+                assertShouldStartClat(false, mNai);
+
+                mNai.linkProperties.addLinkAddress(new LinkAddress("2001:db8::1/64"));
+                assertRequiresClat(true, mNai);
+                assertShouldStartClat(true, mNai);
 
                 mMisc.skip464xlat = true;
-                String errorMsg = msg + String.format(" skip464xlat=%b", mMisc.skip464xlat);
-                assertFalse(errorMsg, Nat464Xlat.requiresClat(mNai));
+                assertRequiresClat(false, mNai);
+                assertShouldStartClat(false, mNai);
 
                 mMisc.skip464xlat = false;
-                errorMsg = msg + String.format(" skip464xlat=%b", mMisc.skip464xlat);
-                assertTrue(errorMsg, Nat464Xlat.requiresClat(mNai));
+                assertRequiresClat(true, mNai);
+                assertShouldStartClat(true, mNai);
+
+                mNai.linkProperties.addLinkAddress(new LinkAddress("192.0.2.2/24"));
+                assertRequiresClat(false, mNai);
+                assertShouldStartClat(false, mNai);
+
+                mNai.linkProperties.removeLinkAddress(new LinkAddress("192.0.2.2/24"));
+                assertRequiresClat(true, mNai);
+                assertShouldStartClat(true, mNai);
+
+                mNai.linkProperties.setNat64Prefix(null);
+                assertRequiresClat(true, mNai);
+                assertShouldStartClat(false, mNai);
+
+                mNai.linkProperties = new LinkProperties(oldLp);
             }
         }
     }
@@ -125,11 +178,13 @@
         Nat464Xlat nat = makeNat464Xlat();
         ArgumentCaptor<LinkProperties> c = ArgumentCaptor.forClass(LinkProperties.class);
 
-        // ConnectivityService starts clat.
+        nat.setNat64Prefix(new IpPrefix(NAT64_PREFIX));
+
+        // Start clat.
         nat.start();
 
         verify(mNms).registerObserver(eq(nat));
-        verify(mNetd).clatdStart(eq(BASE_IFACE));
+        verify(mNetd).clatdStart(eq(BASE_IFACE), eq(NAT64_PREFIX));
 
         // Stacked interface up notification arrives.
         nat.interfaceLinkStateChanged(STACKED_IFACE, true);
@@ -141,22 +196,109 @@
         assertTrue(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
         assertRunning(nat);
 
-        // ConnectivityService stops clat (Network disconnects, IPv4 addr appears, ...).
+        // Stop clat (Network disconnects, IPv4 addr appears, ...).
         nat.stop();
 
         verify(mNetd).clatdStop(eq(BASE_IFACE));
+        verify(mConnectivity, times(2)).handleUpdateLinkProperties(eq(mNai), c.capture());
+        verify(mNms).unregisterObserver(eq(nat));
+        assertTrue(c.getValue().getStackedLinks().isEmpty());
+        assertFalse(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
+        verify(mNetd).resolverStopPrefix64Discovery(eq(NETID));
+        assertIdle(nat);
 
-        // Stacked interface removed notification arrives.
+        // Stacked interface removed notification arrives and is ignored.
         nat.interfaceRemoved(STACKED_IFACE);
         mLooper.dispatchNext();
 
-        verify(mNms).unregisterObserver(eq(nat));
-        verify(mConnectivity, times(2)).handleUpdateLinkProperties(eq(mNai), c.capture());
+        verifyNoMoreInteractions(mNetd, mNms, mConnectivity);
+    }
+
+    private void checkStartStopStart(boolean interfaceRemovedFirst) throws Exception {
+        Nat464Xlat nat = makeNat464Xlat();
+        ArgumentCaptor<LinkProperties> c = ArgumentCaptor.forClass(LinkProperties.class);
+        InOrder inOrder = inOrder(mNetd, mConnectivity);
+
+        nat.setNat64Prefix(new IpPrefix(NAT64_PREFIX));
+
+        nat.start();
+
+        inOrder.verify(mNetd).clatdStart(eq(BASE_IFACE), eq(NAT64_PREFIX));
+
+        // Stacked interface up notification arrives.
+        nat.interfaceLinkStateChanged(STACKED_IFACE, true);
+        mLooper.dispatchNext();
+
+        inOrder.verify(mConnectivity).handleUpdateLinkProperties(eq(mNai), c.capture());
+        assertFalse(c.getValue().getStackedLinks().isEmpty());
+        assertTrue(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
+        assertRunning(nat);
+
+        // ConnectivityService stops clat (Network disconnects, IPv4 addr appears, ...).
+        nat.stop();
+
+        inOrder.verify(mNetd).clatdStop(eq(BASE_IFACE));
+
+        inOrder.verify(mConnectivity, times(1)).handleUpdateLinkProperties(eq(mNai), c.capture());
         assertTrue(c.getValue().getStackedLinks().isEmpty());
         assertFalse(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
         assertIdle(nat);
 
-        verifyNoMoreInteractions(mNetd, mNms, mConnectivity);
+        if (interfaceRemovedFirst) {
+            // Stacked interface removed notification arrives and is ignored.
+            nat.interfaceRemoved(STACKED_IFACE);
+            mLooper.dispatchNext();
+            nat.interfaceLinkStateChanged(STACKED_IFACE, false);
+            mLooper.dispatchNext();
+        }
+
+        assertTrue(c.getValue().getStackedLinks().isEmpty());
+        assertFalse(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
+        assertIdle(nat);
+        inOrder.verifyNoMoreInteractions();
+
+        nat.start();
+
+        inOrder.verify(mNetd).clatdStart(eq(BASE_IFACE), eq(NAT64_PREFIX));
+
+        if (!interfaceRemovedFirst) {
+            // Stacked interface removed notification arrives and is ignored.
+            nat.interfaceRemoved(STACKED_IFACE);
+            mLooper.dispatchNext();
+            nat.interfaceLinkStateChanged(STACKED_IFACE, false);
+            mLooper.dispatchNext();
+        }
+
+        // Stacked interface up notification arrives.
+        nat.interfaceLinkStateChanged(STACKED_IFACE, true);
+        mLooper.dispatchNext();
+
+        inOrder.verify(mConnectivity).handleUpdateLinkProperties(eq(mNai), c.capture());
+        assertFalse(c.getValue().getStackedLinks().isEmpty());
+        assertTrue(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
+        assertRunning(nat);
+
+        // ConnectivityService stops clat again.
+        nat.stop();
+
+        inOrder.verify(mNetd).clatdStop(eq(BASE_IFACE));
+
+        inOrder.verify(mConnectivity, times(1)).handleUpdateLinkProperties(eq(mNai), c.capture());
+        assertTrue(c.getValue().getStackedLinks().isEmpty());
+        assertFalse(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
+        assertIdle(nat);
+
+        inOrder.verifyNoMoreInteractions();
+    }
+
+    @Test
+    public void testStartStopStart() throws Exception {
+        checkStartStopStart(true);
+    }
+
+    @Test
+    public void testStartStopStartBeforeInterfaceRemoved() throws Exception {
+        checkStartStopStart(false);
     }
 
     @Test
@@ -164,11 +306,12 @@
         Nat464Xlat nat = makeNat464Xlat();
         ArgumentCaptor<LinkProperties> c = ArgumentCaptor.forClass(LinkProperties.class);
 
-        // ConnectivityService starts clat.
+        nat.setNat64Prefix(new IpPrefix(NAT64_PREFIX));
+
         nat.start();
 
         verify(mNms).registerObserver(eq(nat));
-        verify(mNetd).clatdStart(eq(BASE_IFACE));
+        verify(mNetd).clatdStart(eq(BASE_IFACE), eq(NAT64_PREFIX));
 
         // Stacked interface up notification arrives.
         nat.interfaceLinkStateChanged(STACKED_IFACE, true);
@@ -184,9 +327,10 @@
         nat.interfaceRemoved(STACKED_IFACE);
         mLooper.dispatchNext();
 
-        verify(mNms).unregisterObserver(eq(nat));
         verify(mNetd).clatdStop(eq(BASE_IFACE));
         verify(mConnectivity, times(2)).handleUpdateLinkProperties(eq(mNai), c.capture());
+        verify(mNms).unregisterObserver(eq(nat));
+        verify(mNetd).resolverStopPrefix64Discovery(eq(NETID));
         assertTrue(c.getValue().getStackedLinks().isEmpty());
         assertFalse(c.getValue().getAllInterfaceNames().contains(STACKED_IFACE));
         assertIdle(nat);
@@ -201,24 +345,25 @@
     public void testStopBeforeClatdStarts() throws Exception {
         Nat464Xlat nat = makeNat464Xlat();
 
-        // ConnectivityService starts clat.
+        nat.setNat64Prefix(new IpPrefix(NAT64_PREFIX));
+
         nat.start();
 
         verify(mNms).registerObserver(eq(nat));
-        verify(mNetd).clatdStart(eq(BASE_IFACE));
+        verify(mNetd).clatdStart(eq(BASE_IFACE), eq(NAT64_PREFIX));
 
         // ConnectivityService immediately stops clat (Network disconnects, IPv4 addr appears, ...)
         nat.stop();
 
-        verify(mNms).unregisterObserver(eq(nat));
         verify(mNetd).clatdStop(eq(BASE_IFACE));
+        verify(mNms).unregisterObserver(eq(nat));
+        verify(mNetd).resolverStopPrefix64Discovery(eq(NETID));
         assertIdle(nat);
 
         // In-flight interface up notification arrives: no-op
         nat.interfaceLinkStateChanged(STACKED_IFACE, true);
         mLooper.dispatchNext();
 
-
         // Interface removed notification arrives after stopClatd() takes effect: no-op.
         nat.interfaceRemoved(STACKED_IFACE);
         mLooper.dispatchNext();
@@ -232,17 +377,19 @@
     public void testStopAndClatdNeverStarts() throws Exception {
         Nat464Xlat nat = makeNat464Xlat();
 
-        // ConnectivityService starts clat.
+        nat.setNat64Prefix(new IpPrefix(NAT64_PREFIX));
+
         nat.start();
 
         verify(mNms).registerObserver(eq(nat));
-        verify(mNetd).clatdStart(eq(BASE_IFACE));
+        verify(mNetd).clatdStart(eq(BASE_IFACE), eq(NAT64_PREFIX));
 
         // ConnectivityService immediately stops clat (Network disconnects, IPv4 addr appears, ...)
         nat.stop();
 
-        verify(mNms).unregisterObserver(eq(nat));
         verify(mNetd).clatdStop(eq(BASE_IFACE));
+        verify(mNms).unregisterObserver(eq(nat));
+        verify(mNetd).resolverStopPrefix64Discovery(eq(NETID));
         assertIdle(nat);
 
         verifyNoMoreInteractions(mNetd, mNms, mConnectivity);
diff --git a/tests/utils/SleepUtils/AlarmService/Android.mk b/tests/utils/SleepUtils/AlarmService/Android.mk
deleted file mode 100644
index 9022f03..0000000
--- a/tests/utils/SleepUtils/AlarmService/Android.mk
+++ /dev/null
@@ -1,26 +0,0 @@
-#
-# 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.
-#
-
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_SRC_FILES += \
-    src/com/android/testing/alarmservice/Alarm.aidl
-LOCAL_PACKAGE_NAME := SleepUtilsAlarmService
-LOCAL_SDK_VERSION := 7
-include $(BUILD_PACKAGE)
diff --git a/tests/utils/SleepUtils/AlarmService/AndroidManifest.xml b/tests/utils/SleepUtils/AlarmService/AndroidManifest.xml
deleted file mode 100644
index 1b6de39..0000000
--- a/tests/utils/SleepUtils/AlarmService/AndroidManifest.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 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. -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.testing.alarmservice" >
-
-    <uses-sdk android:minSdkVersion="7" />
-    <uses-permission android:name="android.permission.WAKE_LOCK" />
-
-    <application android:label="Sleep Utils Alarm Service">
-        <service android:name=".AlarmService"
-            android:label="Sleep Utils Alarm Service"
-            android:exported="true"
-            android:enabled="true">
-            <intent-filter>
-                <action android:name="com.android.testing.ALARM_SERVICE" />
-            </intent-filter>
-        </service>
-        <receiver android:name=".WakeUpCall">
-            <intent-filter>
-                <action android:name="com.android.testing.alarmservice.WAKEUP" />
-            </intent-filter>
-        </receiver>
-    </application>
-</manifest>
diff --git a/tests/utils/SleepUtils/AlarmService/src/com/android/testing/alarmservice/Alarm.aidl b/tests/utils/SleepUtils/AlarmService/src/com/android/testing/alarmservice/Alarm.aidl
deleted file mode 100644
index 62a8c48..0000000
--- a/tests/utils/SleepUtils/AlarmService/src/com/android/testing/alarmservice/Alarm.aidl
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * 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.testing.alarmservice;
-
-interface Alarm {
-    int prepare();
-    int setAlarmAndWait(long timeoutMills);
-    int done();
-}
\ No newline at end of file
diff --git a/tests/utils/SleepUtils/AlarmService/src/com/android/testing/alarmservice/AlarmImpl.java b/tests/utils/SleepUtils/AlarmService/src/com/android/testing/alarmservice/AlarmImpl.java
deleted file mode 100644
index 122d55d..0000000
--- a/tests/utils/SleepUtils/AlarmService/src/com/android/testing/alarmservice/AlarmImpl.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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.testing.alarmservice;
-
-import android.app.AlarmManager;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.Intent;
-import android.os.RemoteException;
-import android.os.SystemClock;
-import android.util.Log;
-
-import com.android.testing.alarmservice.Alarm.Stub;
-
-public class AlarmImpl extends Stub {
-
-    private static final String LOG_TAG = AlarmImpl.class.getSimpleName();
-
-    private Context mContext;
-
-    public AlarmImpl(Context context) {
-        super();
-        mContext = context;
-    }
-
-    @Override
-    public int prepare() throws RemoteException {
-        WakeUpController.getController().getWakeLock().acquire();
-        Log.d(LOG_TAG, "AlarmService prepared, wake lock acquired");
-        return 0;
-    }
-
-    @Override
-    public int setAlarmAndWait(long timeoutMills) throws RemoteException {
-        // calculate when device should be waken up
-        long atTime = SystemClock.elapsedRealtime() + timeoutMills;
-        AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
-        Intent wakupIntent = new Intent(WakeUpCall.WAKEUP_CALL);
-        PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, wakupIntent, 0);
-        // set alarm, which will be delivered in form of the wakeupIntent
-        am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, atTime, pi);
-        Log.d(LOG_TAG, String.format("Alarm set: %d, giving up wake lock", atTime));
-        Object lock = WakeUpController.getController().getWakeSync();
-        // release wakelock and wait for the lock to be poked from the broadcast receiver
-        WakeUpController.getController().getWakeLock().release();
-        // does not really matter if device enters suspend before we start waiting on lock
-        synchronized (lock) {
-            try {
-                lock.wait();
-            } catch (InterruptedException e) {
-            }
-        }
-        Log.d(LOG_TAG, String.format("Alarm triggered, done waiting"));
-        return 0;
-    }
-
-    @Override
-    public int done() throws RemoteException {
-        WakeUpController.getController().getWakeLock().release();
-        return 0;
-    }
-
-}
diff --git a/tests/utils/SleepUtils/AlarmService/src/com/android/testing/alarmservice/AlarmService.java b/tests/utils/SleepUtils/AlarmService/src/com/android/testing/alarmservice/AlarmService.java
deleted file mode 100644
index 576a1cf..0000000
--- a/tests/utils/SleepUtils/AlarmService/src/com/android/testing/alarmservice/AlarmService.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * 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.testing.alarmservice;
-
-import android.app.Service;
-import android.content.Context;
-import android.content.Intent;
-import android.os.IBinder;
-
-public class AlarmService extends Service {
-
-    private AlarmImpl mAlarmImpl = null;
-    static Context sContext;
-
-    @Override
-    public void onCreate() {
-        super.onCreate();
-        sContext = this;
-    }
-
-    @Override
-    public IBinder onBind(Intent intent) {
-        return getAlarmImpl();
-    }
-
-    private AlarmImpl getAlarmImpl() {
-        if (mAlarmImpl == null) {
-            mAlarmImpl = new AlarmImpl(this);
-        }
-        return mAlarmImpl;
-    }
-
-    @Override
-    public void onDestroy() {
-        sContext = null;
-        super.onDestroy();
-    }
-}
diff --git a/tests/utils/SleepUtils/AlarmService/src/com/android/testing/alarmservice/WakeUpCall.java b/tests/utils/SleepUtils/AlarmService/src/com/android/testing/alarmservice/WakeUpCall.java
deleted file mode 100644
index f4bb4db..0000000
--- a/tests/utils/SleepUtils/AlarmService/src/com/android/testing/alarmservice/WakeUpCall.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.testing.alarmservice;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-
-/**
- * The receiver for the alarm we set
- *
- */
-public class WakeUpCall extends BroadcastReceiver {
-
-    public static final String WAKEUP_CALL = "com.android.testing.alarmservice.WAKEUP";
-
-    @Override
-    public void onReceive(Context context, Intent intent) {
-        // we acquire wakelock without release because user is supposed to manually release it
-        WakeUpController.getController().getWakeLock().acquire();
-        Object lock = WakeUpController.getController().getWakeSync();
-        synchronized (lock) {
-            // poke the lock so the service side can be woken from waiting on the lock
-            lock.notifyAll();
-        }
-    }
-
-}
diff --git a/tests/utils/SleepUtils/AlarmService/src/com/android/testing/alarmservice/WakeUpController.java b/tests/utils/SleepUtils/AlarmService/src/com/android/testing/alarmservice/WakeUpController.java
deleted file mode 100644
index 478371f..0000000
--- a/tests/utils/SleepUtils/AlarmService/src/com/android/testing/alarmservice/WakeUpController.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.testing.alarmservice;
-
-import android.content.Context;
-import android.os.PowerManager;
-import android.os.PowerManager.WakeLock;
-import android.util.Log;
-
-/**
- * A singleton used for controlling and sharing of states/wakelocks
- *
- */
-public class WakeUpController {
-
-    private static final String LOG_TAG = WakeUpController.class.getName();
-    private static WakeUpController mController = null;
-    private WakeLock mWakeLock = null;
-    private Object mWakeSync = new Object();
-
-    private WakeUpController() {
-        Log.i(LOG_TAG, "Created instance: 0x" + Integer.toHexString(this.hashCode()));
-    }
-
-    public static synchronized WakeUpController getController() {
-        if (mController == null) {
-            mController = new WakeUpController();
-        }
-        return mController;
-    }
-
-    public WakeLock getWakeLock() {
-        if (mWakeLock == null) {
-            PowerManager pm =
-                    (PowerManager) AlarmService.sContext.getSystemService(Context.POWER_SERVICE);
-            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "testing-alarmservice");
-            Log.i(LOG_TAG, "Create wakelock: 0x" + Integer.toHexString(mWakeLock.hashCode()));
-        }
-        return mWakeLock;
-    }
-
-    public Object getWakeSync() {
-        return mWakeSync;
-    }
-}
diff --git a/tests/utils/SleepUtils/Android.mk b/tests/utils/SleepUtils/Android.mk
deleted file mode 100644
index 0e65e22..0000000
--- a/tests/utils/SleepUtils/Android.mk
+++ /dev/null
@@ -1,2 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(call all-makefiles-under, $(LOCAL_PATH))
diff --git a/tests/utils/SleepUtils/README b/tests/utils/SleepUtils/README
deleted file mode 100644
index bfe07da..0000000
--- a/tests/utils/SleepUtils/README
+++ /dev/null
@@ -1,23 +0,0 @@
-This folder contains utils to properly perform timed suspend and wakeup.
-
-AlarmService - a service that client can bind to and perform:
-1) holding wakelock (singleton to this service)
-2) setting alarm for a specified period and releasing the wakelock; service
-   call will block until alarm has been triggered and the wakelock is held
-3) releasing the wakelock
-
-SleepHelper - a self instrumentation meant as a convenient way to trigger
-the service functions from command line. Corresponding to service function
-above, supported operations are:
-1) holding wakelock
-am instrument -w -e command prepare \
-  com.android.testing.sleephelper/.SetAlarm
-
-2) setting alarm and wait til triggered
-am instrument -w -e command set_wait \
-  -e param <time in ms> com.android.testing.sleephelper/.SetAlarm
-Note: for the function to work properly, "-w" parameter is required
-
-3) releasing wakelock
-am instrument -w -e command done \
-  com.android.testing.sleephelper/.SetAlarm
diff --git a/tests/utils/SleepUtils/SleepHelper/Android.mk b/tests/utils/SleepUtils/SleepHelper/Android.mk
deleted file mode 100644
index f8267fd..0000000
--- a/tests/utils/SleepUtils/SleepHelper/Android.mk
+++ /dev/null
@@ -1,29 +0,0 @@
-#
-# 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.
-#
-
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-# Only compile source java files in this apk.
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_SRC_FILES += \
-    ../AlarmService/src/com/android/testing/alarmservice/Alarm.aidl
-LOCAL_SDK_VERSION := 7
-LOCAL_PACKAGE_NAME := SleepUtilsSleepHelper
-
-include $(BUILD_PACKAGE)
diff --git a/tests/utils/SleepUtils/SleepHelper/AndroidManifest.xml b/tests/utils/SleepUtils/SleepHelper/AndroidManifest.xml
deleted file mode 100644
index 0f1d491..0000000
--- a/tests/utils/SleepUtils/SleepHelper/AndroidManifest.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 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. -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.testing.sleephelper">
-
-    <uses-sdk android:minSdkVersion="7" />
-    <instrumentation android:label="Sleep Helper"
-                     android:name="com.android.testing.sleephelper.SetAlarm"
-                     android:targetPackage="com.android.testing.sleephelper" />
-
-    <application android:label="Sleep Utils Sleep Helper">
-        <uses-library android:name="android.test.runner" />
-    </application>
-</manifest>
diff --git a/tests/utils/SleepUtils/SleepHelper/src/com/android/testing/sleephelper/SetAlarm.java b/tests/utils/SleepUtils/SleepHelper/src/com/android/testing/sleephelper/SetAlarm.java
deleted file mode 100644
index b558741..0000000
--- a/tests/utils/SleepUtils/SleepHelper/src/com/android/testing/sleephelper/SetAlarm.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * 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.testing.sleephelper;
-
-import android.app.Activity;
-import android.app.Instrumentation;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.ServiceConnection;
-import android.os.Bundle;
-import android.os.Debug;
-import android.os.IBinder;
-import android.os.RemoteException;
-import android.util.Log;
-
-import com.android.testing.alarmservice.Alarm;
-
-public class SetAlarm extends Instrumentation {
-
-    private static final String COMMAND = "command";
-    private static final String PARAM = "param";
-    private static final String CMD_PREPARE = "prepare";
-    private static final String CMD_SET = "set_wait";
-    private static final String CMD_DONE = "done";
-    private static final String SERVICE_ACTION = "com.android.testing.ALARM_SERVICE";
-    private static final String SERVICE_PKG = "com.android.testing.alarmservice";
-    private static final String LOG_TAG = SetAlarm.class.getSimpleName();
-
-    private Alarm mAlarmService = null;
-    private Bundle mArgs = null;
-    private String mCommand = null;
-    private Intent mServceIntent = new Intent(SERVICE_ACTION).setPackage(SERVICE_PKG);
-
-    private ServiceConnection mConn = new ServiceConnection() {
-        @Override
-        public void onServiceDisconnected(ComponentName name) {
-            Log.d(LOG_TAG, "Service disconnected.");
-            mAlarmService = null;
-            errorFinish("service disconnected");
-        }
-
-        @Override
-        public void onServiceConnected(ComponentName name, IBinder service) {
-            Log.d(LOG_TAG, "Service connected.");
-            mAlarmService = Alarm.Stub.asInterface(service);
-            handleCommands();
-        }
-    };
-
-
-    private void handleCommands() {
-        if (CMD_PREPARE.equals(mCommand)) {
-            callPrepare();
-        } else if (CMD_SET.equals(mCommand)) {
-            String paramString = mArgs.getString(PARAM);
-            if (paramString == null) {
-                errorFinish("argument expected for alarm time");
-            }
-            long timeout = -1;
-            try {
-                timeout = Long.parseLong(paramString);
-            } catch (NumberFormatException nfe) {
-                errorFinish("a number argument is expected");
-            }
-            callSetAndWait(timeout);
-        } else if (CMD_DONE.equals(mCommand)) {
-            callDone();
-        } else {
-            errorFinish("Unrecognized command: " + mCommand);
-        }
-        finish(Activity.RESULT_OK, new Bundle());
-    }
-
-    @Override
-    public void onCreate(Bundle arguments) {
-        super.onCreate(arguments);
-        mCommand = arguments.getString(COMMAND);
-        if ("true".equals(arguments.getString("debug"))) {
-            Debug.waitForDebugger();
-        }
-        if (mCommand == null) {
-            errorFinish("No command specified");
-        }
-        mArgs = arguments;
-        connectToAlarmService();
-    }
-
-    private void errorFinish(String msg) {
-        Bundle ret = new Bundle();
-        ret.putString("error", msg);
-        finish(Activity.RESULT_CANCELED, ret);
-    }
-
-    private void connectToAlarmService() {
-        // start the service with an intent, this ensures the service keeps running after unbind
-        ComponentName cn = getContext().startService(mServceIntent);
-        if (cn == null) {
-            errorFinish("failed to start service");
-        }
-        if (!getContext().bindService(mServceIntent, mConn, Context.BIND_AUTO_CREATE)) {
-            errorFinish("failed to bind service");
-        }
-    }
-
-    private void callPrepare() {
-        try {
-            mAlarmService.prepare();
-        } catch (RemoteException e) {
-            errorFinish("RemoteExeption in prepare()");
-        } finally {
-            getContext().unbindService(mConn);
-        }
-    }
-
-    private void callDone() {
-        try {
-            mAlarmService.done();
-        } catch (RemoteException e) {
-            errorFinish("RemoteExeption in prepare()");
-        } finally {
-            getContext().unbindService(mConn);
-        }
-        // explicitly stop the service (started in prepare()) so that the service is now free
-        // to be reclaimed
-        getContext().stopService(mServceIntent);
-    }
-
-    private void callSetAndWait(long timeoutMills) {
-        try {
-            mAlarmService.setAlarmAndWait(timeoutMills);
-        } catch (RemoteException e) {
-            errorFinish("RemoteExeption in setAlarmAndWait()");
-        } finally {
-            getContext().unbindService(mConn);
-        }
-    }
-}
diff --git a/tests/utils/SleepUtils/WakeLoopService/Android.mk b/tests/utils/SleepUtils/WakeLoopService/Android.mk
deleted file mode 100644
index a8a944b..0000000
--- a/tests/utils/SleepUtils/WakeLoopService/Android.mk
+++ /dev/null
@@ -1,24 +0,0 @@
-#
-# Copyright (C) 2014 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_PACKAGE_NAME := WakeupLoopService
-LOCAL_SDK_VERSION := 7
-include $(BUILD_PACKAGE)
diff --git a/tests/utils/SleepUtils/WakeLoopService/AndroidManifest.xml b/tests/utils/SleepUtils/WakeLoopService/AndroidManifest.xml
deleted file mode 100644
index a7028c4..0000000
--- a/tests/utils/SleepUtils/WakeLoopService/AndroidManifest.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 The Android Open Source Project Licensed under the
-    Apache License, Version 2.0 (the "License"); you may not use this file except
-    in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
-    Unless required by applicable law or agreed to in writing, software distributed
-    under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
-    OR CONDITIONS OF ANY KIND, either express or implied. See the License for
-    the specific language governing permissions and limitations under the License. -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.test.wakeuploop" >
-
-    <uses-sdk android:minSdkVersion="7" />
-    <uses-permission android:name="android.permission.WAKE_LOCK" />
-    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-
-    <application android:label="Auto Wakeup Loop">
-        <service android:name=".WakeLoopService"
-            android:label="Wakup Loop Service"
-            android:exported="true"
-            android:enabled="true">
-            <intent-filter>
-                <action android:name="android.test.wakeuploop.WAKEUP_SERVICE" />
-            </intent-filter>
-        </service>
-        <receiver android:name=".WakeUpCall">
-            <intent-filter>
-                <action android:name="android.test.wakeuploop.WAKEUP" />
-            </intent-filter>
-        </receiver>
-    </application>
-</manifest>
diff --git a/tests/utils/SleepUtils/WakeLoopService/src/android/test/wakeuploop/FileUtil.java b/tests/utils/SleepUtils/WakeLoopService/src/android/test/wakeuploop/FileUtil.java
deleted file mode 100644
index c8b075b..0000000
--- a/tests/utils/SleepUtils/WakeLoopService/src/android/test/wakeuploop/FileUtil.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2014 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.test.wakeuploop;
-
-import android.util.Log;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-public class FileUtil {
-
-    private static FileUtil sInst = null;
-    private static DateFormat sDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
-
-    private FileUtil() {};
-
-    public static FileUtil get() {
-        if (sInst == null) {
-            sInst = new FileUtil();
-        }
-        return sInst;
-    }
-
-    public void writeDateToFile(File file) {
-        try {
-            FileOutputStream fos = new FileOutputStream(file);
-            fos.write(sDateFormat.format(new Date()).getBytes());
-            fos.write('\n');
-            fos.flush();
-            fos.close();
-        } catch (IOException ioe) {
-            Log.e("FileUtil", "exception writing date to file", ioe);
-        }
-    }
-}
diff --git a/tests/utils/SleepUtils/WakeLoopService/src/android/test/wakeuploop/WakeLoopService.java b/tests/utils/SleepUtils/WakeLoopService/src/android/test/wakeuploop/WakeLoopService.java
deleted file mode 100644
index 4f557b8..0000000
--- a/tests/utils/SleepUtils/WakeLoopService/src/android/test/wakeuploop/WakeLoopService.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2014 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.test.wakeuploop;
-
-import android.app.AlarmManager;
-import android.app.PendingIntent;
-import android.app.Service;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Environment;
-import android.os.Handler;
-import android.os.IBinder;
-import android.os.Message;
-import android.os.Messenger;
-import android.os.SystemClock;
-import android.util.Log;
-
-import java.io.File;
-
-public class WakeLoopService extends Service {
-
-    private static final String LOG_TAG = WakeLoopService.class.getSimpleName();
-    static final String WAKEUP_INTERNAL = "WAKEUP_INTERVAL";
-    static final String MAX_LOOP = "MAX_LOOP";
-    static final String STOP_CALLBACK = "STOP_CALLBACK";
-    static final String THIS_LOOP = "THIS_LOOP";
-    static final int MSG_STOP_SERVICE = 0xd1ed1e;
-
-    private final Handler mHandler = new Handler() {
-        public void handleMessage(Message msg) {
-            if (msg.what == MSG_STOP_SERVICE) {
-                stopSelf();
-            } else {
-                super.handleMessage(msg);
-            }
-        };
-    };
-
-    @Override
-    public IBinder onBind(Intent intent) {
-        // no binding, just start via intent
-        return null;
-    }
-
-    @Override
-    public int onStartCommand(Intent intent, int flags, int startId) {
-        // get wakeup interval from intent
-        long wakeupInterval = intent.getLongExtra(WAKEUP_INTERNAL, 0);
-        long maxLoop = intent.getLongExtra(MAX_LOOP, 0);
-
-        if (wakeupInterval == 0) {
-            // stop and error
-            Log.e(LOG_TAG, "No wakeup interval specified, not starting the service");
-            stopSelf();
-            return START_NOT_STICKY;
-        }
-        FileUtil.get().writeDateToFile(new File(Environment.getExternalStorageDirectory(),
-                "wakeup-loop-start.txt"));
-        Log.d(LOG_TAG, String.format("WakeLoop: STARTED interval = %d, total loop = %d",
-                wakeupInterval, maxLoop));
-        // calculate when device should be waken up
-        long atTime = SystemClock.elapsedRealtime() + wakeupInterval;
-        AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
-        Intent wakupIntent = new Intent(WakeUpCall.WAKEUP_CALL)
-            .putExtra(WAKEUP_INTERNAL, wakeupInterval)
-            .putExtra(MAX_LOOP, maxLoop)
-            .putExtra(THIS_LOOP, 0L)
-            .putExtra(STOP_CALLBACK, new Messenger(mHandler));
-        PendingIntent pi = PendingIntent.getBroadcast(this, 0, wakupIntent,
-                PendingIntent.FLAG_UPDATE_CURRENT);
-        // set alarm, which will be delivered in form of the wakeupIntent
-        am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, atTime, pi);
-        return START_NOT_STICKY;
-    }
-
-    @Override
-    public void onDestroy() {
-        Log.d(LOG_TAG, "WakeLoop: STOPPED");
-        // cancel alarms first
-        Intent intent = new Intent(WakeUpCall.WAKEUP_CALL)
-            .putExtra(WakeUpCall.CANCEL, "true");
-        sendBroadcast(intent);
-    }
-}
diff --git a/tests/utils/SleepUtils/WakeLoopService/src/android/test/wakeuploop/WakeUpCall.java b/tests/utils/SleepUtils/WakeLoopService/src/android/test/wakeuploop/WakeUpCall.java
deleted file mode 100644
index 8347bbf0..0000000
--- a/tests/utils/SleepUtils/WakeLoopService/src/android/test/wakeuploop/WakeUpCall.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (C) 2014 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.test.wakeuploop;
-
-import android.app.AlarmManager;
-import android.app.PendingIntent;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Environment;
-import android.os.Message;
-import android.os.Messenger;
-import android.os.PowerManager;
-import android.os.PowerManager.WakeLock;
-import android.os.RemoteException;
-import android.os.SystemClock;
-import android.util.Log;
-
-import java.io.File;
-
-/**
- * The receiver for the alarm we set
- *
- */
-public class WakeUpCall extends BroadcastReceiver {
-    private static final String LOG_TAG = WakeUpCall.class.getSimpleName();
-    static final String WAKEUP_CALL = "android.test.wakeuploop.WAKEUP";
-    static final String CANCEL = "CANCEL";
-
-    @Override
-    public void onReceive(Context context, Intent intent) {
-        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
-        boolean cancel = intent.hasExtra(CANCEL);
-        if (!cancel) {
-            long maxLoop = intent.getLongExtra(WakeLoopService.MAX_LOOP, 0);
-            long wakeupInterval = intent.getLongExtra(WakeLoopService.WAKEUP_INTERNAL, 0);
-            long thisLoop = intent.getLongExtra(WakeLoopService.THIS_LOOP, -1);
-            Log.d(LOG_TAG, String.format("incoming: interval = %d, max loop = %d, this loop = %d",
-                    wakeupInterval, maxLoop, thisLoop));
-            if (thisLoop == -1) {
-                Log.e(LOG_TAG, "no valid loop count received, trying to stop service");
-                stopService(intent);
-                return;
-            }
-            if (wakeupInterval == 0) {
-                Log.e(LOG_TAG, "no valid wakeup interval received, trying to stop service");
-                stopService(intent);
-                return;
-            }
-            thisLoop++;
-            Log.d(LOG_TAG, String.format("WakeLoop - iteration %d of %d", thisLoop, maxLoop));
-            if (thisLoop == maxLoop) {
-                // when maxLoop is 0, we loop forever, so not checking that case
-                // here
-                Log.d(LOG_TAG, "reached max loop count, stopping service");
-                stopService(intent);
-                return;
-            }
-            screenOn(context);
-            FileUtil.get().writeDateToFile(
-                    new File(Environment.getExternalStorageDirectory(), "wakeup-loop.txt"));
-            // calculate when device should be waken up
-            long atTime = SystemClock.elapsedRealtime() + wakeupInterval;
-            intent.putExtra(WakeLoopService.THIS_LOOP, thisLoop);
-            PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent,
-                    PendingIntent.FLAG_UPDATE_CURRENT);
-            // set alarm, which will be delivered in form of the wakeupIntent
-            am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, atTime, pi);
-        } else {
-            // cancel alarms
-            Log.d(LOG_TAG, "cancelling future alarms on request");
-            am.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
-        }
-    }
-
-    private void stopService(Intent i) {
-        Messenger msgr = i.getParcelableExtra(WakeLoopService.STOP_CALLBACK);
-        if (msgr == null) {
-            Log.e(LOG_TAG, "no stop service callback found, cannot stop");
-        } else {
-            Message msg = new Message();
-            msg.what = WakeLoopService.MSG_STOP_SERVICE;
-            try {
-                msgr.send(msg);
-            } catch (RemoteException e) {
-                Log.e(LOG_TAG, "ignored remoted exception while attempting to stop service", e);
-            }
-        }
-    }
-
-    private void screenOn(Context context) {
-        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
-        @SuppressWarnings("deprecation")
-        WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK |
-                PowerManager.ACQUIRE_CAUSES_WAKEUP, LOG_TAG);
-        wl.acquire(500);
-    }
-}
diff --git a/tools/apilint/apilint.py b/tools/apilint/apilint.py
index 59e89f5..ef405e4 100644
--- a/tools/apilint/apilint.py
+++ b/tools/apilint/apilint.py
@@ -208,13 +208,14 @@
 
 
 class Package():
+    NAME = re.compile("package(?: .*)? ([A-Za-z.]+)")
+
     def __init__(self, line, raw, blame):
         self.line = line
         self.raw = raw.strip(" {;")
         self.blame = blame
 
-        raw = raw.split()
-        self.name = raw[raw.index("package")+1]
+        self.name = Package.NAME.match(raw).group(1)
         self.name_path = self.name.split(".")
 
     def __repr__(self):
@@ -1108,6 +1109,9 @@
     if not has_build:
         warn(clazz, None, None, "Missing build() method")
 
+    if "final" not in clazz.split:
+        error(clazz, None, None, "Builder should be final")
+
 
 def verify_aidl(clazz):
     """Catch people exposing raw AIDL."""
diff --git a/tools/apilint/apilint_test.py b/tools/apilint/apilint_test.py
index 3716bf9..c10ef15 100644
--- a/tools/apilint/apilint_test.py
+++ b/tools/apilint/apilint_test.py
@@ -369,5 +369,21 @@
         m = self._method('method @NonNull public @NonNull String @NonNull [] split(@NonNull String, int);')
         self.assertEquals('java.lang.String[]', m.typ)
 
+class PackageTests(unittest.TestCase):
+    def _package(self, raw):
+        return apilint.Package(123, raw, "blame")
+
+    def test_regular_package(self):
+        p = self._package("package an.pref.int {")
+        self.assertEquals('an.pref.int', p.name)
+
+    def test_annotation_package(self):
+        p = self._package("package @RestrictTo(a.b.C) an.pref.int {")
+        self.assertEquals('an.pref.int', p.name)
+
+    def test_multi_annotation_package(self):
+        p = self._package("package @Rt(a.b.L_G_P) @RestrictTo(a.b.C) an.pref.int {")
+        self.assertEquals('an.pref.int', p.name)
+
 if __name__ == "__main__":
     unittest.main()