Merge "DO NOT MERGE base: getDataUsageInfo get cycle validation"
diff --git a/Android.bp b/Android.bp
index 70438d2..e0e8062 100644
--- a/Android.bp
+++ b/Android.bp
@@ -25,8 +25,8 @@
 //
 // READ ME: ########################################################
 
-java_library {
-    name: "framework",
+java_defaults {
+    name: "framework-defaults",
     installable: true,
 
     srcs: [
@@ -695,12 +695,38 @@
         "libmedia2_jni",
     ],
 
-    javac_shard_size: 150,
-
     dxflags: [
         "--core-library",
         "--multi-dex",
     ],
+
+}
+
+java_library {
+    name: "framework",
+    defaults: ["framework-defaults"],
+    javac_shard_size: 150,
+}
+
+java_library {
+    name: "framework-annotation-proc",
+    defaults: ["framework-defaults"],
+    // Use UsedByApps annotation processor
+    annotation_processors: ["unsupportedappusage-annotation-processor"],
+    // b/25860419: annotation processors must be explicitly specified for grok
+    annotation_processor_classes: [
+        "android.processor.unsupportedappusage.UsedByAppsProcessor",
+    ],
+}
+
+// A host library including just UnsupportedAppUsage.java so that the annotation
+// processor can also use this annotation.
+java_library_host {
+    name: "unsupportedappusage-annotation",
+    srcs: [
+        "core/java/android/annotation/IntDef.java",
+        "core/java/android/annotation/UnsupportedAppUsage.java",
+    ],
 }
 
 // A temporary build target that is conditionally included on the bootclasspath if
@@ -1065,7 +1091,7 @@
         "ext",
         "framework",
         "voip-common",
-        "android.test.mock",
+        "android.test.mock.impl",
     ],
     local_sourcepaths: frameworks_base_subdirs,
     html_dirs: [
@@ -1202,7 +1228,7 @@
         "ext",
         "framework",
         "voip-common",
-        "android.test.mock",
+        "android.test.mock.impl",
     ],
     local_sourcepaths: frameworks_base_subdirs,
     installable: false,
diff --git a/Android.mk b/Android.mk
index 988c009..5c4c237 100644
--- a/Android.mk
+++ b/Android.mk
@@ -322,6 +322,11 @@
 	( unzip -qo $< -d $(OUT_DOCS)/offline-sdk && touch -f $@ ) || exit 1
 
 # ==== hiddenapi lists =======================================
+.KATI_RESTAT: \
+	$(INTERNAL_PLATFORM_HIDDENAPI_WHITELIST) \
+	$(INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST) \
+	$(INTERNAL_PLATFORM_HIDDENAPI_DARK_GREYLIST) \
+	$(INTERNAL_PLATFORM_HIDDENAPI_BLACKLIST)
 $(INTERNAL_PLATFORM_HIDDENAPI_WHITELIST): \
     .KATI_IMPLICIT_OUTPUTS := \
         $(INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST) \
@@ -346,10 +351,14 @@
 	                   $(INTERNAL_PLATFORM_HIDDENAPI_PRIVATE_LIST)) \
 	        $(PRIVATE_GREYLIST_INPUTS) \
 	    --input-blacklists frameworks/base/config/hiddenapi-force-blacklist.txt \
-	    --output-whitelist $(INTERNAL_PLATFORM_HIDDENAPI_WHITELIST) \
-	    --output-light-greylist $(INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST) \
-	    --output-dark-greylist $(INTERNAL_PLATFORM_HIDDENAPI_DARK_GREYLIST) \
-	    --output-blacklist $(INTERNAL_PLATFORM_HIDDENAPI_BLACKLIST)
+	    --output-whitelist $(INTERNAL_PLATFORM_HIDDENAPI_WHITELIST).tmp \
+	    --output-light-greylist $(INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST).tmp \
+	    --output-dark-greylist $(INTERNAL_PLATFORM_HIDDENAPI_DARK_GREYLIST).tmp \
+	    --output-blacklist $(INTERNAL_PLATFORM_HIDDENAPI_BLACKLIST).tmp
+	$(call commit-change-for-toc,$(INTERNAL_PLATFORM_HIDDENAPI_WHITELIST))
+	$(call commit-change-for-toc,$(INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST))
+	$(call commit-change-for-toc,$(INTERNAL_PLATFORM_HIDDENAPI_DARK_GREYLIST))
+	$(call commit-change-for-toc,$(INTERNAL_PLATFORM_HIDDENAPI_BLACKLIST))
 
 # Include subdirectory makefiles
 # ============================================================
diff --git a/PREUPLOAD.cfg b/PREUPLOAD.cfg
index 1f8ab21..07b0ae1 100644
--- a/PREUPLOAD.cfg
+++ b/PREUPLOAD.cfg
@@ -14,3 +14,5 @@
 strings_lint_hook = ${REPO_ROOT}/frameworks/base/tools/stringslint/stringslint_sha.sh ${PREUPLOAD_COMMIT}
 
 hidden_api_txt_hook = ${REPO_ROOT}/frameworks/base/tools/hiddenapi/checksorted_sha.sh ${PREUPLOAD_COMMIT} ${REPO_ROOT}
+
+owners_hook = ${REPO_ROOT}/frameworks/base/tools/aosp/aosp_sha.sh ${PREUPLOAD_COMMIT} "OWNERS$"
diff --git a/api/current.txt b/api/current.txt
index 6a70b14..fe8ee50 100755
--- a/api/current.txt
+++ b/api/current.txt
@@ -42440,6 +42440,7 @@
   }
 
   public class SubscriptionManager {
+    method public void addOnOpportunisticSubscriptionsChangedListener(java.util.concurrent.Executor, android.telephony.SubscriptionManager.OnOpportunisticSubscriptionsChangedListener);
     method public void addOnSubscriptionsChangedListener(android.telephony.SubscriptionManager.OnSubscriptionsChangedListener);
     method public boolean canManageSubscription(android.telephony.SubscriptionInfo);
     method public static deprecated android.telephony.SubscriptionManager from(android.content.Context);
@@ -42453,8 +42454,10 @@
     method public static int getDefaultSmsSubscriptionId();
     method public static int getDefaultSubscriptionId();
     method public static int getDefaultVoiceSubscriptionId();
+    method public static int[] getSubscriptionIds(int);
     method public java.util.List<android.telephony.SubscriptionPlan> getSubscriptionPlans(int);
     method public boolean isNetworkRoaming(int);
+    method public void removeOnOpportunisticSubscriptionsChangedListener(android.telephony.SubscriptionManager.OnOpportunisticSubscriptionsChangedListener);
     method public void removeOnSubscriptionsChangedListener(android.telephony.SubscriptionManager.OnSubscriptionsChangedListener);
     method public void setSubscriptionOverrideCongested(int, boolean, long);
     method public void setSubscriptionOverrideUnmetered(int, boolean, long);
@@ -42470,6 +42473,11 @@
     field public static final int INVALID_SUBSCRIPTION_ID = -1; // 0xffffffff
   }
 
+  public static class SubscriptionManager.OnOpportunisticSubscriptionsChangedListener {
+    ctor public SubscriptionManager.OnOpportunisticSubscriptionsChangedListener();
+    method public void onOpportunisticSubscriptionsChanged();
+  }
+
   public static class SubscriptionManager.OnSubscriptionsChangedListener {
     ctor public SubscriptionManager.OnSubscriptionsChangedListener();
     method public void onSubscriptionsChanged();
diff --git a/cmds/statsd/src/external/Perfetto.cpp b/cmds/statsd/src/external/Perfetto.cpp
index 0554483..c1f9a64 100644
--- a/cmds/statsd/src/external/Perfetto.cpp
+++ b/cmds/statsd/src/external/Perfetto.cpp
@@ -105,9 +105,9 @@
 
     readPipe.reset();  // Close the read end (owned by the child process).
 
-    // Using fopen() because fwrite() has the right logic to chunking write()
+    // Using fdopen() because fwrite() has the right logic to chunking write()
     // over a pipe (see __sfvwrite()).
-    FILE* writePipeStream = fdopen(writePipe.get(), "wb");
+    FILE* writePipeStream = android::base::Fdopen(std::move(writePipe), "wb");
     if (!writePipeStream) {
         ALOGE("fdopen() failed while calling the Perfetto client: %s", strerror(errno));
         return false;
diff --git a/config/boot-image-profile.txt b/config/boot-image-profile.txt
index 9ca0745..3567605 100644
--- a/config/boot-image-profile.txt
+++ b/config/boot-image-profile.txt
@@ -11825,6 +11825,7 @@
 HPLlibcore/io/BlockGuardOs;->rename(Ljava/lang/String;Ljava/lang/String;)V
 HPLlibcore/io/BlockGuardOs;->sendto(Ljava/io/FileDescriptor;[BIIILjava/net/SocketAddress;)I
 HPLlibcore/io/BlockGuardOs;->write(Ljava/io/FileDescriptor;Ljava/nio/ByteBuffer;)I
+HPLlibcore/io/ForwardingOs;->android_fdsan_exchange_owner_tag(Ljava/io/FileDescriptor;JJ)V
 HPLlibcore/io/ForwardingOs;->munlock(JJ)V
 HPLlibcore/io/ForwardingOs;->munmap(JJ)V
 HPLlibcore/io/ForwardingOs;->setsockoptByte(Ljava/io/FileDescriptor;III)V
@@ -51627,6 +51628,7 @@
 HSPLlibcore/io/IoUtils$FileReader;-><init>(Ljava/lang/String;)V
 HSPLlibcore/io/IoUtils$FileReader;->readFully()Llibcore/io/IoUtils$FileReader;
 HSPLlibcore/io/IoUtils$FileReader;->toByteArray()[B
+HSPLlibcore/io/IoUtils;->acquireRawFd(Ljava/io/FileDescriptor;)I
 HSPLlibcore/io/IoUtils;->canOpenReadOnly(Ljava/lang/String;)Z
 HSPLlibcore/io/IoUtils;->close(Ljava/io/FileDescriptor;)V
 HSPLlibcore/io/IoUtils;->closeQuietly(Ljava/io/FileDescriptor;)V
@@ -51634,6 +51636,7 @@
 HSPLlibcore/io/IoUtils;->readFileAsByteArray(Ljava/lang/String;)[B
 HSPLlibcore/io/IoUtils;->readFileAsString(Ljava/lang/String;)Ljava/lang/String;
 HSPLlibcore/io/IoUtils;->setBlocking(Ljava/io/FileDescriptor;Z)V
+HSPLlibcore/io/IoUtils;->setFdOwner(Ljava/io/FileDescriptor;Ljava/lang/Object;)V
 HSPLlibcore/io/Linux;->read(Ljava/io/FileDescriptor;[BII)I
 HSPLlibcore/io/Linux;->recvfrom(Ljava/io/FileDescriptor;[BIIILjava/net/InetSocketAddress;)I
 HSPLlibcore/io/Linux;->sendto(Ljava/io/FileDescriptor;[BIIILjava/net/InetAddress;I)I
diff --git a/core/java/android/appwidget/AppWidgetProviderInfo.java b/core/java/android/appwidget/AppWidgetProviderInfo.java
index 53315cc..d148afb 100644
--- a/core/java/android/appwidget/AppWidgetProviderInfo.java
+++ b/core/java/android/appwidget/AppWidgetProviderInfo.java
@@ -400,7 +400,7 @@
         that.initialLayout = this.initialLayout;
         that.initialKeyguardLayout = this.initialKeyguardLayout;
         that.configure = this.configure == null ? null : this.configure.clone();
-        that.label = this.label == null ? null : this.label.substring(0);
+        that.label = this.label;
         that.icon = this.icon;
         that.previewImage = this.previewImage;
         that.autoAdvanceViewId = this.autoAdvanceViewId;
diff --git a/core/java/android/content/pm/ApplicationInfo.java b/core/java/android/content/pm/ApplicationInfo.java
index 243d7d8..7cdae22 100644
--- a/core/java/android/content/pm/ApplicationInfo.java
+++ b/core/java/android/content/pm/ApplicationInfo.java
@@ -621,6 +621,13 @@
      */
     public static final int PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY = 1 << 20;
 
+    /**
+     * Indicates whether this package requires access to non-SDK APIs.
+     * Only system apps and tests are allowed to use this property.
+     * @hide
+     */
+    public static final int PRIVATE_FLAG_USES_NON_SDK_API = 1 << 22;
+
     /** @hide */
     @IntDef(flag = true, prefix = { "PRIVATE_FLAG_" }, value = {
             PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE,
@@ -1001,13 +1008,6 @@
     public String appComponentFactory;
 
     /**
-     * Indicates whether this package requires access to non-SDK APIs. Only system apps
-     * and tests are allowed to use this property.
-     * @hide
-     */
-    public boolean usesNonSdkApi;
-
-    /**
      * The category of this app. Categories are used to cluster multiple apps
      * together into meaningful groups, such as when summarizing battery,
      * network, or disk usage. Apps should only define this value when they fit
@@ -1283,6 +1283,7 @@
                 pw.println(prefix + "category=" + category);
             }
             pw.println(prefix + "HiddenApiEnforcementPolicy=" + getHiddenApiEnforcementPolicy());
+            pw.println(prefix + "usesNonSdkApi=" + usesNonSdkApi());
         }
         super.dumpBack(pw, prefix);
     }
@@ -1704,11 +1705,18 @@
         return SystemConfig.getInstance().getHiddenApiWhitelistedApps().contains(packageName);
     }
 
+    /**
+     * @hide
+     */
+    public boolean usesNonSdkApi() {
+        return (privateFlags & PRIVATE_FLAG_USES_NON_SDK_API) != 0;
+    }
+
     private boolean isAllowedToUseHiddenApis() {
         if (isSignedWithPlatformKey()) {
             return true;
         } else if (isSystemApp() || isUpdatedSystemApp()) {
-            return usesNonSdkApi || isPackageWhitelistedForHiddenApis();
+            return usesNonSdkApi() || isPackageWhitelistedForHiddenApis();
         } else {
             return false;
         }
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index b7be5a7..7eefe55 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -3580,8 +3580,10 @@
             ai.appComponentFactory = buildClassName(ai.packageName, factory, outError);
         }
 
-        ai.usesNonSdkApi = sa.getBoolean(
-                com.android.internal.R.styleable.AndroidManifestApplication_usesNonSdkApi, false);
+        if (sa.getBoolean(
+                com.android.internal.R.styleable.AndroidManifestApplication_usesNonSdkApi, false)) {
+            ai.privateFlags |= ApplicationInfo.PRIVATE_FLAG_USES_NON_SDK_API;
+        }
 
         if (outError[0] == null) {
             CharSequence pname;
diff --git a/core/java/android/hardware/Camera.java b/core/java/android/hardware/Camera.java
index d8cdf60..8e96f56 100644
--- a/core/java/android/hardware/Camera.java
+++ b/core/java/android/hardware/Camera.java
@@ -575,9 +575,7 @@
     /**
      * An empty Camera for testing purpose.
      */
-    Camera() {
-        initAppOps();
-    }
+    Camera() {}
 
     private void initAppOps() {
         IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
diff --git a/core/java/android/hardware/camera2/CameraCharacteristics.java b/core/java/android/hardware/camera2/CameraCharacteristics.java
index 9b18e9a..35584ae 100644
--- a/core/java/android/hardware/camera2/CameraCharacteristics.java
+++ b/core/java/android/hardware/camera2/CameraCharacteristics.java
@@ -1255,7 +1255,9 @@
      * <p>If this device is the largest or only camera device with a given facing, then this
      * position will be <code>(0, 0, 0)</code>; a camera device with a lens optical center located 3 cm
      * from the main sensor along the +X axis (to the right from the user's perspective) will
-     * report <code>(0.03, 0, 0)</code>.</p>
+     * report <code>(0.03, 0, 0)</code>.  Note that this means that, for many computer vision
+     * applications, the position needs to be negated to convert it to a translation from the
+     * camera to the origin.</p>
      * <p>To transform a pixel coordinates between two cameras facing the same direction, first
      * the source camera {@link CameraCharacteristics#LENS_DISTORTION android.lens.distortion} must be corrected for.  Then the source
      * camera {@link CameraCharacteristics#LENS_INTRINSIC_CALIBRATION android.lens.intrinsicCalibration} needs to be applied, followed by the
@@ -1267,7 +1269,8 @@
      * <p>To compare this against a real image from the destination camera, the destination camera
      * image then needs to be corrected for radial distortion before comparison or sampling.</p>
      * <p>When {@link CameraCharacteristics#LENS_POSE_REFERENCE android.lens.poseReference} is GYROSCOPE, then this position is relative to
-     * the center of the primary gyroscope on the device.</p>
+     * the center of the primary gyroscope on the device. The axis definitions are the same as
+     * with PRIMARY_CAMERA.</p>
      * <p><b>Units</b>: Meters</p>
      * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
      *
@@ -1299,13 +1302,15 @@
      * </code></pre>
      * <p>which can then be combined with the camera pose rotation
      * <code>R</code> and translation <code>t</code> ({@link CameraCharacteristics#LENS_POSE_ROTATION android.lens.poseRotation} and
-     * {@link CameraCharacteristics#LENS_POSE_TRANSLATION android.lens.poseTranslation}, respective) to calculate the
+     * {@link CameraCharacteristics#LENS_POSE_TRANSLATION android.lens.poseTranslation}, respectively) to calculate the
      * complete transform from world coordinates to pixel
      * coordinates:</p>
-     * <pre><code>P = [ K 0   * [ R t
-     *      0 1 ]     0 1 ]
+     * <pre><code>P = [ K 0   * [ R -Rt
+     *      0 1 ]      0 1 ]
      * </code></pre>
-     * <p>and with <code>p_w</code> being a point in the world coordinate system
+     * <p>(Note the negation of poseTranslation when mapping from camera
+     * to world coordinates, and multiplication by the rotation).</p>
+     * <p>With <code>p_w</code> being a point in the world coordinate system
      * and <code>p_s</code> being a point in the camera active pixel array
      * coordinate system, and with the mapping including the
      * homogeneous division by z:</p>
@@ -1327,6 +1332,13 @@
      * activeArraySize rectangle), to determine the final pixel
      * coordinate of the world point for processed (non-RAW)
      * output buffers.</p>
+     * <p>For camera devices, the center of pixel <code>(x,y)</code> is located at
+     * coordinate <code>(x + 0.5, y + 0.5)</code>.  So on a device with a
+     * precorrection active array of size <code>(10,10)</code>, the valid pixel
+     * indices go from <code>(0,0)-(9,9)</code>, and an perfectly-built camera would
+     * have an optical center at the exact center of the pixel grid, at
+     * coordinates <code>(5.0, 5.0)</code>, which is the top-left corner of pixel
+     * <code>(5,5)</code>.</p>
      * <p><b>Units</b>:
      * Pixels in the
      * {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize}
diff --git a/core/java/android/hardware/camera2/CameraMetadata.java b/core/java/android/hardware/camera2/CameraMetadata.java
index 1275a85..caa99d5 100644
--- a/core/java/android/hardware/camera2/CameraMetadata.java
+++ b/core/java/android/hardware/camera2/CameraMetadata.java
@@ -819,11 +819,11 @@
      * camera in the list of supported camera devices.</p>
      * <p>This capability requires the camera device to support the following:</p>
      * <ul>
-     * <li>This camera device must list the following static metadata entries in {@link android.hardware.camera2.CameraCharacteristics }:<ul>
-     * <li>android.logicalMultiCamera.physicalIds</li>
-     * <li>{@link CameraCharacteristics#LOGICAL_MULTI_CAMERA_SENSOR_SYNC_TYPE android.logicalMultiCamera.sensorSyncType}</li>
-     * </ul>
-     * </li>
+     * <li>The IDs of underlying physical cameras are returned via
+     *   {@link android.hardware.camera2.CameraCharacteristics#getPhysicalCameraIds }.</li>
+     * <li>This camera device must list static metadata
+     *   {@link CameraCharacteristics#LOGICAL_MULTI_CAMERA_SENSOR_SYNC_TYPE android.logicalMultiCamera.sensorSyncType} in
+     *   {@link android.hardware.camera2.CameraCharacteristics }.</li>
      * <li>The underlying physical cameras' static metadata must list the following entries,
      *   so that the application can correlate pixels from the physical streams:<ul>
      * <li>{@link CameraCharacteristics#LENS_POSE_REFERENCE android.lens.poseReference}</li>
diff --git a/core/java/android/hardware/camera2/CaptureRequest.java b/core/java/android/hardware/camera2/CaptureRequest.java
index 0b92b0c..4a20468 100644
--- a/core/java/android/hardware/camera2/CaptureRequest.java
+++ b/core/java/android/hardware/camera2/CaptureRequest.java
@@ -2530,7 +2530,7 @@
      * outputs will crop horizontally (pillarbox), and 16:9
      * streams will match exactly. These additional crops will
      * be centered within the crop region.</p>
-     * <p>If the coordinate system is android.sensor.info.activeArraysSize, the width and height
+     * <p>If the coordinate system is {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize}, the width and height
      * of the crop region cannot be set to be smaller than
      * <code>floor( activeArraySize.width / {@link CameraCharacteristics#SCALER_AVAILABLE_MAX_DIGITAL_ZOOM android.scaler.availableMaxDigitalZoom} )</code> and
      * <code>floor( activeArraySize.height / {@link CameraCharacteristics#SCALER_AVAILABLE_MAX_DIGITAL_ZOOM android.scaler.availableMaxDigitalZoom} )</code>, respectively.</p>
@@ -2871,8 +2871,14 @@
             new Key<Integer>("android.statistics.lensShadingMapMode", int.class);
 
     /**
-     * <p>A control for selecting whether OIS position information is included in output
-     * result metadata.</p>
+     * <p>A control for selecting whether optical stabilization (OIS) position
+     * information is included in output result metadata.</p>
+     * <p>Since optical image stabilization generally involves motion much faster than the duration
+     * of individualq image exposure, multiple OIS samples can be included for a single capture
+     * result. For example, if the OIS reporting operates at 200 Hz, a typical camera operating
+     * at 30fps may have 6-7 OIS samples per capture result. This information can be combined
+     * with the rolling shutter skew to account for lens motion during image exposure in
+     * post-processing algorithms.</p>
      * <p><b>Possible values:</b>
      * <ul>
      *   <li>{@link #STATISTICS_OIS_DATA_MODE_OFF OFF}</li>
@@ -3272,14 +3278,28 @@
      * any correction at all would slow down capture rate.  Every output stream will have a
      * similar amount of enhancement applied.</p>
      * <p>The correction only applies to processed outputs such as YUV, JPEG, or DEPTH16; it is not
-     * applied to any RAW output. Metadata coordinates such as face rectangles or metering
-     * regions are also not affected by correction.</p>
+     * applied to any RAW output.</p>
      * <p>This control will be on by default on devices that support this control. Applications
      * disabling distortion correction need to pay extra attention with the coordinate system of
      * metering regions, crop region, and face rectangles. When distortion correction is OFF,
      * metadata coordinates follow the coordinate system of
      * {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize}. When distortion is not OFF, metadata
-     * coordinates follow the coordinate system of {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize}.</p>
+     * coordinates follow the coordinate system of {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize}.  The
+     * camera device will map these metadata fields to match the corrected image produced by the
+     * camera device, for both capture requests and results.  However, this mapping is not very
+     * precise, since rectangles do not generally map to rectangles when corrected.  Only linear
+     * scaling between the active array and precorrection active array coordinates is
+     * performed. Applications that require precise correction of metadata need to undo that
+     * linear scaling, and apply a more complete correction that takes into the account the app's
+     * own requirements.</p>
+     * <p>The full list of metadata that is affected in this way by distortion correction is:</p>
+     * <ul>
+     * <li>{@link CaptureRequest#CONTROL_AF_REGIONS android.control.afRegions}</li>
+     * <li>{@link CaptureRequest#CONTROL_AE_REGIONS android.control.aeRegions}</li>
+     * <li>{@link CaptureRequest#CONTROL_AWB_REGIONS android.control.awbRegions}</li>
+     * <li>{@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion}</li>
+     * <li>{@link CaptureResult#STATISTICS_FACES android.statistics.faces}</li>
+     * </ul>
      * <p><b>Possible values:</b>
      * <ul>
      *   <li>{@link #DISTORTION_CORRECTION_MODE_OFF OFF}</li>
@@ -3290,10 +3310,15 @@
      * {@link CameraCharacteristics#DISTORTION_CORRECTION_AVAILABLE_MODES android.distortionCorrection.availableModes}</p>
      * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
      *
+     * @see CaptureRequest#CONTROL_AE_REGIONS
+     * @see CaptureRequest#CONTROL_AF_REGIONS
+     * @see CaptureRequest#CONTROL_AWB_REGIONS
      * @see CameraCharacteristics#DISTORTION_CORRECTION_AVAILABLE_MODES
      * @see CameraCharacteristics#LENS_DISTORTION
+     * @see CaptureRequest#SCALER_CROP_REGION
      * @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
      * @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
+     * @see CaptureResult#STATISTICS_FACES
      * @see #DISTORTION_CORRECTION_MODE_OFF
      * @see #DISTORTION_CORRECTION_MODE_FAST
      * @see #DISTORTION_CORRECTION_MODE_HIGH_QUALITY
diff --git a/core/java/android/hardware/camera2/CaptureResult.java b/core/java/android/hardware/camera2/CaptureResult.java
index e007d28..1e894e8 100644
--- a/core/java/android/hardware/camera2/CaptureResult.java
+++ b/core/java/android/hardware/camera2/CaptureResult.java
@@ -2858,7 +2858,9 @@
      * <p>If this device is the largest or only camera device with a given facing, then this
      * position will be <code>(0, 0, 0)</code>; a camera device with a lens optical center located 3 cm
      * from the main sensor along the +X axis (to the right from the user's perspective) will
-     * report <code>(0.03, 0, 0)</code>.</p>
+     * report <code>(0.03, 0, 0)</code>.  Note that this means that, for many computer vision
+     * applications, the position needs to be negated to convert it to a translation from the
+     * camera to the origin.</p>
      * <p>To transform a pixel coordinates between two cameras facing the same direction, first
      * the source camera {@link CameraCharacteristics#LENS_DISTORTION android.lens.distortion} must be corrected for.  Then the source
      * camera {@link CameraCharacteristics#LENS_INTRINSIC_CALIBRATION android.lens.intrinsicCalibration} needs to be applied, followed by the
@@ -2870,7 +2872,8 @@
      * <p>To compare this against a real image from the destination camera, the destination camera
      * image then needs to be corrected for radial distortion before comparison or sampling.</p>
      * <p>When {@link CameraCharacteristics#LENS_POSE_REFERENCE android.lens.poseReference} is GYROSCOPE, then this position is relative to
-     * the center of the primary gyroscope on the device.</p>
+     * the center of the primary gyroscope on the device. The axis definitions are the same as
+     * with PRIMARY_CAMERA.</p>
      * <p><b>Units</b>: Meters</p>
      * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
      *
@@ -2902,13 +2905,15 @@
      * </code></pre>
      * <p>which can then be combined with the camera pose rotation
      * <code>R</code> and translation <code>t</code> ({@link CameraCharacteristics#LENS_POSE_ROTATION android.lens.poseRotation} and
-     * {@link CameraCharacteristics#LENS_POSE_TRANSLATION android.lens.poseTranslation}, respective) to calculate the
+     * {@link CameraCharacteristics#LENS_POSE_TRANSLATION android.lens.poseTranslation}, respectively) to calculate the
      * complete transform from world coordinates to pixel
      * coordinates:</p>
-     * <pre><code>P = [ K 0   * [ R t
-     *      0 1 ]     0 1 ]
+     * <pre><code>P = [ K 0   * [ R -Rt
+     *      0 1 ]      0 1 ]
      * </code></pre>
-     * <p>and with <code>p_w</code> being a point in the world coordinate system
+     * <p>(Note the negation of poseTranslation when mapping from camera
+     * to world coordinates, and multiplication by the rotation).</p>
+     * <p>With <code>p_w</code> being a point in the world coordinate system
      * and <code>p_s</code> being a point in the camera active pixel array
      * coordinate system, and with the mapping including the
      * homogeneous division by z:</p>
@@ -2930,6 +2935,13 @@
      * activeArraySize rectangle), to determine the final pixel
      * coordinate of the world point for processed (non-RAW)
      * output buffers.</p>
+     * <p>For camera devices, the center of pixel <code>(x,y)</code> is located at
+     * coordinate <code>(x + 0.5, y + 0.5)</code>.  So on a device with a
+     * precorrection active array of size <code>(10,10)</code>, the valid pixel
+     * indices go from <code>(0,0)-(9,9)</code>, and an perfectly-built camera would
+     * have an optical center at the exact center of the pixel grid, at
+     * coordinates <code>(5.0, 5.0)</code>, which is the top-left corner of pixel
+     * <code>(5,5)</code>.</p>
      * <p><b>Units</b>:
      * Pixels in the
      * {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize}
@@ -3194,7 +3206,7 @@
      * outputs will crop horizontally (pillarbox), and 16:9
      * streams will match exactly. These additional crops will
      * be centered within the crop region.</p>
-     * <p>If the coordinate system is android.sensor.info.activeArraysSize, the width and height
+     * <p>If the coordinate system is {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize}, the width and height
      * of the crop region cannot be set to be smaller than
      * <code>floor( activeArraySize.width / {@link CameraCharacteristics#SCALER_AVAILABLE_MAX_DIGITAL_ZOOM android.scaler.availableMaxDigitalZoom} )</code> and
      * <code>floor( activeArraySize.height / {@link CameraCharacteristics#SCALER_AVAILABLE_MAX_DIGITAL_ZOOM android.scaler.availableMaxDigitalZoom} )</code>, respectively.</p>
@@ -4083,8 +4095,14 @@
             new Key<Integer>("android.statistics.lensShadingMapMode", int.class);
 
     /**
-     * <p>A control for selecting whether OIS position information is included in output
-     * result metadata.</p>
+     * <p>A control for selecting whether optical stabilization (OIS) position
+     * information is included in output result metadata.</p>
+     * <p>Since optical image stabilization generally involves motion much faster than the duration
+     * of individualq image exposure, multiple OIS samples can be included for a single capture
+     * result. For example, if the OIS reporting operates at 200 Hz, a typical camera operating
+     * at 30fps may have 6-7 OIS samples per capture result. This information can be combined
+     * with the rolling shutter skew to account for lens motion during image exposure in
+     * post-processing algorithms.</p>
      * <p><b>Possible values:</b>
      * <ul>
      *   <li>{@link #STATISTICS_OIS_DATA_MODE_OFF OFF}</li>
@@ -4118,11 +4136,15 @@
     /**
      * <p>An array of shifts of OIS samples, in x direction.</p>
      * <p>The array contains the amount of shifts in x direction, in pixels, based on OIS samples.
-     * A positive value is a shift from left to right in active array coordinate system. For
-     * example, if the optical center is (1000, 500) in active array coordinates, a shift of
-     * (3, 0) puts the new optical center at (1003, 500).</p>
+     * A positive value is a shift from left to right in the pre-correction active array
+     * coordinate system. For example, if the optical center is (1000, 500) in pre-correction
+     * active array coordinates, a shift of (3, 0) puts the new optical center at (1003, 500).</p>
      * <p>The number of shifts must match the number of timestamps in
      * android.statistics.oisTimestamps.</p>
+     * <p>The OIS samples are not affected by whether lens distortion correction is enabled (on
+     * supporting devices). They are always reported in pre-correction active array coordinates,
+     * since the scaling of OIS shifts would depend on the specific spot on the sensor the shift
+     * is needed.</p>
      * <p><b>Units</b>: Pixels in active array.</p>
      * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
      * @hide
@@ -4133,11 +4155,15 @@
     /**
      * <p>An array of shifts of OIS samples, in y direction.</p>
      * <p>The array contains the amount of shifts in y direction, in pixels, based on OIS samples.
-     * A positive value is a shift from top to bottom in active array coordinate system. For
-     * example, if the optical center is (1000, 500) in active array coordinates, a shift of
-     * (0, 5) puts the new optical center at (1000, 505).</p>
+     * A positive value is a shift from top to bottom in pre-correction active array coordinate
+     * system. For example, if the optical center is (1000, 500) in active array coordinates, a
+     * shift of (0, 5) puts the new optical center at (1000, 505).</p>
      * <p>The number of shifts must match the number of timestamps in
      * android.statistics.oisTimestamps.</p>
+     * <p>The OIS samples are not affected by whether lens distortion correction is enabled (on
+     * supporting devices). They are always reported in pre-correction active array coordinates,
+     * since the scaling of OIS shifts would depend on the specific spot on the sensor the shift
+     * is needed.</p>
      * <p><b>Units</b>: Pixels in active array.</p>
      * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
      * @hide
@@ -4146,15 +4172,21 @@
             new Key<float[]>("android.statistics.oisYShifts", float[].class);
 
     /**
-     * <p>An array of OIS samples.</p>
+     * <p>An array of optical stabilization (OIS) position samples.</p>
      * <p>Each OIS sample contains the timestamp and the amount of shifts in x and y direction,
      * in pixels, of the OIS sample.</p>
-     * <p>A positive value for a shift in x direction is a shift from left to right in active array
-     * coordinate system. For example, if the optical center is (1000, 500) in active array
-     * coordinates, a shift of (3, 0) puts the new optical center at (1003, 500).</p>
-     * <p>A positive value for a shift in y direction is a shift from top to bottom in active array
-     * coordinate system. For example, if the optical center is (1000, 500) in active array
-     * coordinates, a shift of (0, 5) puts the new optical center at (1000, 505).</p>
+     * <p>A positive value for a shift in x direction is a shift from left to right in the
+     * pre-correction active array coordinate system. For example, if the optical center is
+     * (1000, 500) in pre-correction active array coordinates, a shift of (3, 0) puts the new
+     * optical center at (1003, 500).</p>
+     * <p>A positive value for a shift in y direction is a shift from top to bottom in
+     * pre-correction active array coordinate system. For example, if the optical center is
+     * (1000, 500) in active array coordinates, a shift of (0, 5) puts the new optical center at
+     * (1000, 505).</p>
+     * <p>The OIS samples are not affected by whether lens distortion correction is enabled (on
+     * supporting devices). They are always reported in pre-correction active array coordinates,
+     * since the scaling of OIS shifts would depend on the specific spot on the sensor the shift
+     * is needed.</p>
      * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
      */
     @PublicKey
@@ -4584,14 +4616,28 @@
      * any correction at all would slow down capture rate.  Every output stream will have a
      * similar amount of enhancement applied.</p>
      * <p>The correction only applies to processed outputs such as YUV, JPEG, or DEPTH16; it is not
-     * applied to any RAW output. Metadata coordinates such as face rectangles or metering
-     * regions are also not affected by correction.</p>
+     * applied to any RAW output.</p>
      * <p>This control will be on by default on devices that support this control. Applications
      * disabling distortion correction need to pay extra attention with the coordinate system of
      * metering regions, crop region, and face rectangles. When distortion correction is OFF,
      * metadata coordinates follow the coordinate system of
      * {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize}. When distortion is not OFF, metadata
-     * coordinates follow the coordinate system of {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize}.</p>
+     * coordinates follow the coordinate system of {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize}.  The
+     * camera device will map these metadata fields to match the corrected image produced by the
+     * camera device, for both capture requests and results.  However, this mapping is not very
+     * precise, since rectangles do not generally map to rectangles when corrected.  Only linear
+     * scaling between the active array and precorrection active array coordinates is
+     * performed. Applications that require precise correction of metadata need to undo that
+     * linear scaling, and apply a more complete correction that takes into the account the app's
+     * own requirements.</p>
+     * <p>The full list of metadata that is affected in this way by distortion correction is:</p>
+     * <ul>
+     * <li>{@link CaptureRequest#CONTROL_AF_REGIONS android.control.afRegions}</li>
+     * <li>{@link CaptureRequest#CONTROL_AE_REGIONS android.control.aeRegions}</li>
+     * <li>{@link CaptureRequest#CONTROL_AWB_REGIONS android.control.awbRegions}</li>
+     * <li>{@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion}</li>
+     * <li>{@link CaptureResult#STATISTICS_FACES android.statistics.faces}</li>
+     * </ul>
      * <p><b>Possible values:</b>
      * <ul>
      *   <li>{@link #DISTORTION_CORRECTION_MODE_OFF OFF}</li>
@@ -4602,10 +4648,15 @@
      * {@link CameraCharacteristics#DISTORTION_CORRECTION_AVAILABLE_MODES android.distortionCorrection.availableModes}</p>
      * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
      *
+     * @see CaptureRequest#CONTROL_AE_REGIONS
+     * @see CaptureRequest#CONTROL_AF_REGIONS
+     * @see CaptureRequest#CONTROL_AWB_REGIONS
      * @see CameraCharacteristics#DISTORTION_CORRECTION_AVAILABLE_MODES
      * @see CameraCharacteristics#LENS_DISTORTION
+     * @see CaptureRequest#SCALER_CROP_REGION
      * @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
      * @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
+     * @see CaptureResult#STATISTICS_FACES
      * @see #DISTORTION_CORRECTION_MODE_OFF
      * @see #DISTORTION_CORRECTION_MODE_FAST
      * @see #DISTORTION_CORRECTION_MODE_HIGH_QUALITY
diff --git a/data/etc/platform.xml b/data/etc/platform.xml
index b3f05dc..6f52fbd 100644
--- a/data/etc/platform.xml
+++ b/data/etc/platform.xml
@@ -182,11 +182,11 @@
          code to link against. -->
 
     <library name="android.test.base"
-            file="/system/framework/android.test.base.jar" />
+            file="/system/framework/android.test.base.impl.jar" />
     <library name="android.test.mock"
-            file="/system/framework/android.test.mock.jar" />
+            file="/system/framework/android.test.mock.impl.jar" />
     <library name="android.test.runner"
-            file="/system/framework/android.test.runner.jar" />
+            file="/system/framework/android.test.runner.impl.jar" />
 
     <!-- These are the standard packages that are white-listed to always have internet
          access while in power save mode, even if they aren't in the foreground. -->
diff --git a/data/keyboards/Generic.kcm b/data/keyboards/Generic.kcm
index d0565ca..1ab4c63 100644
--- a/data/keyboards/Generic.kcm
+++ b/data/keyboards/Generic.kcm
@@ -540,7 +540,7 @@
 }
 
 key BUTTON_MODE {
-    base:                               fallback MENU
+    base:                               fallback HOME
 }
 
 key BUTTON_1 {
diff --git a/data/keyboards/Vendor_045e_Product_02e0.kl b/data/keyboards/Vendor_045e_Product_02e0.kl
index 1012fb1..1dd8e15 100644
--- a/data/keyboards/Vendor_045e_Product_02e0.kl
+++ b/data/keyboards/Vendor_045e_Product_02e0.kl
@@ -56,4 +56,4 @@
 key 0x137    BUTTON_START
 
 # Xbox key
-key 0x8b    HOME
\ No newline at end of file
+key 0x8b    BUTTON_MODE
\ No newline at end of file
diff --git a/data/keyboards/Vendor_054c_Product_0268.kl b/data/keyboards/Vendor_054c_Product_0268.kl
index 7c60137..522db3c 100644
--- a/data/keyboards/Vendor_054c_Product_0268.kl
+++ b/data/keyboards/Vendor_054c_Product_0268.kl
@@ -35,7 +35,7 @@
 key 0x122    BUTTON_THUMBR
 
 # PS key
-key 0x2d0    HOME
+key 0x2d0    BUTTON_MODE
 
 # Left Analog Stick
 axis 0x00    X
diff --git a/media/java/android/media/AudioAttributes.java b/media/java/android/media/AudioAttributes.java
index e8bc622..5ad7365 100644
--- a/media/java/android/media/AudioAttributes.java
+++ b/media/java/android/media/AudioAttributes.java
@@ -715,6 +715,7 @@
                     break;
                 case AudioSystem.STREAM_TTS:
                     mContentType = CONTENT_TYPE_SONIFICATION;
+                    mFlags |= FLAG_BEACON;
                     break;
                 case AudioSystem.STREAM_ACCESSIBILITY:
                     mContentType = CONTENT_TYPE_SPEECH;
@@ -1035,10 +1036,14 @@
             return fromGetVolumeControlStream ?
                     AudioSystem.STREAM_SYSTEM : AudioSystem.STREAM_SYSTEM_ENFORCED;
         }
-        if ((aa.getFlags() & FLAG_SCO) == FLAG_SCO) {
+        if ((aa.getAllFlags() & FLAG_SCO) == FLAG_SCO) {
             return fromGetVolumeControlStream ?
                     AudioSystem.STREAM_VOICE_CALL : AudioSystem.STREAM_BLUETOOTH_SCO;
         }
+        if ((aa.getAllFlags() & FLAG_BEACON) == FLAG_BEACON) {
+            return fromGetVolumeControlStream ?
+                    AudioSystem.STREAM_MUSIC : AudioSystem.STREAM_TTS;
+        }
 
         // usage to stream type mapping
         switch (aa.getUsage()) {
diff --git a/packages/CaptivePortalLogin/Android.mk b/packages/CaptivePortalLogin/Android.mk
index 8a96b16..7dc23ff 100644
--- a/packages/CaptivePortalLogin/Android.mk
+++ b/packages/CaptivePortalLogin/Android.mk
@@ -2,7 +2,7 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_TAGS := optional
-LOCAL_STATIC_JAVA_LIBRARIES := android-support-v4 services.net
+LOCAL_STATIC_JAVA_LIBRARIES := android-support-v4
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/packages/SettingsLib/Android.bp b/packages/SettingsLib/Android.bp
new file mode 100644
index 0000000..4791517
--- /dev/null
+++ b/packages/SettingsLib/Android.bp
@@ -0,0 +1,25 @@
+android_library {
+
+    name: "SettingsLib",
+
+    libs: [
+        "androidx.annotation_annotation",
+        "androidx.legacy_legacy-support-v4",
+        "androidx.recyclerview_recyclerview",
+        "androidx.preference_preference",
+        "androidx.appcompat_appcompat",
+        "androidx.lifecycle_lifecycle-runtime",
+    ],
+
+    // ANDROIDMK TRANSLATION ERROR: unsupported assignment to LOCAL_SHARED_JAVA_LIBRARIES
+    // LOCAL_SHARED_JAVA_LIBRARIES := androidx.lifecycle_lifecycle-common
+
+    resource_dirs: ["res"],
+
+    srcs: ["src/**/*.java"],
+
+    min_sdk_version: "21",
+
+}
+
+// For the test package.
diff --git a/packages/SettingsLib/Android.mk b/packages/SettingsLib/Android.mk
deleted file mode 100644
index 96012c1..0000000
--- a/packages/SettingsLib/Android.mk
+++ /dev/null
@@ -1,34 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_USE_AAPT2 := true
-
-LOCAL_AAPT2_ONLY := true
-
-LOCAL_MODULE := SettingsLib
-
-LOCAL_JAVA_LIBRARIES := \
-    androidx.annotation_annotation
-
-LOCAL_SHARED_ANDROID_LIBRARIES := \
-    androidx.legacy_legacy-support-v4 \
-    androidx.recyclerview_recyclerview \
-    androidx.preference_preference \
-    androidx.appcompat_appcompat \
-    androidx.lifecycle_lifecycle-runtime
-
-LOCAL_SHARED_JAVA_LIBRARIES := \
-    androidx.lifecycle_lifecycle-common
-
-LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
-
-LOCAL_JAR_EXCLUDE_FILES := none
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_MIN_SDK_VERSION := 21
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-# For the test package.
-include $(call all-makefiles-under, $(LOCAL_PATH))
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/MapProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/MapProfile.java
index aa7a7af..511c4ce 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/MapProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/MapProfile.java
@@ -32,11 +32,10 @@
 import java.util.List;
 
 /**
- * MapProfile handles Bluetooth MAP profile.
+ * MapProfile handles the Bluetooth MAP MSE role
  */
 public class MapProfile implements LocalBluetoothProfile {
     private static final String TAG = "MapProfile";
-    private static boolean V = true;
 
     private BluetoothMap mService;
     private boolean mIsProfileReady;
@@ -60,7 +59,7 @@
             implements BluetoothProfile.ServiceListener {
 
         public void onServiceConnected(int profile, BluetoothProfile proxy) {
-            if (V) Log.d(TAG,"Bluetooth service connected");
+            Log.d(TAG, "Bluetooth service connected");
             mService = (BluetoothMap) proxy;
             // We just bound to the service, so refresh the UI for any connected MAP devices.
             List<BluetoothDevice> deviceList = mService.getConnectedDevices();
@@ -82,14 +81,14 @@
         }
 
         public void onServiceDisconnected(int profile) {
-            if (V) Log.d(TAG,"Bluetooth service disconnected");
+            Log.d(TAG, "Bluetooth service disconnected");
             mProfileManager.callServiceDisconnectedListeners();
             mIsProfileReady=false;
         }
     }
 
     public boolean isProfileReady() {
-        if(V) Log.d(TAG,"isProfileReady(): "+ mIsProfileReady);
+        Log.d(TAG, "isProfileReady(): " + mIsProfileReady);
         return mIsProfileReady;
     }
 
@@ -117,45 +116,45 @@
     }
 
     public boolean connect(BluetoothDevice device) {
-        if(V)Log.d(TAG,"connect() - should not get called");
+        Log.d(TAG, "connect() - should not get called");
         return false; // MAP never connects out
     }
 
     public boolean disconnect(BluetoothDevice device) {
-        if (mService == null) return false;
-        List<BluetoothDevice> deviceList = mService.getConnectedDevices();
-        if (!deviceList.isEmpty() && deviceList.get(0).equals(device)) {
-            if (mService.getPriority(device) > BluetoothProfile.PRIORITY_ON) {
-                mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
-            }
-            return mService.disconnect(device);
-        } else {
+        if (mService == null) {
             return false;
         }
+        if (mService.getPriority(device) > BluetoothProfile.PRIORITY_ON) {
+            mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+        }
+        return mService.disconnect(device);
     }
 
     public int getConnectionStatus(BluetoothDevice device) {
-        if (mService == null) return BluetoothProfile.STATE_DISCONNECTED;
-        List<BluetoothDevice> deviceList = mService.getConnectedDevices();
-        if(V) Log.d(TAG,"getConnectionStatus: status is: "+ mService.getConnectionState(device));
-
-        return !deviceList.isEmpty() && deviceList.get(0).equals(device)
-                ? mService.getConnectionState(device)
-                : BluetoothProfile.STATE_DISCONNECTED;
+        if (mService == null) {
+            return BluetoothProfile.STATE_DISCONNECTED;
+        }
+        return mService.getConnectionState(device);
     }
 
     public boolean isPreferred(BluetoothDevice device) {
-        if (mService == null) return false;
+        if (mService == null) {
+            return false;
+        }
         return mService.getPriority(device) > BluetoothProfile.PRIORITY_OFF;
     }
 
     public int getPreferred(BluetoothDevice device) {
-        if (mService == null) return BluetoothProfile.PRIORITY_OFF;
+        if (mService == null) {
+            return BluetoothProfile.PRIORITY_OFF;
+        }
         return mService.getPriority(device);
     }
 
     public void setPreferred(BluetoothDevice device, boolean preferred) {
-        if (mService == null) return;
+        if (mService == null) {
+            return;
+        }
         if (preferred) {
             if (mService.getPriority(device) < BluetoothProfile.PRIORITY_ON) {
                 mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
@@ -166,7 +165,9 @@
     }
 
     public List<BluetoothDevice> getConnectedDevices() {
-        if (mService == null) return new ArrayList<BluetoothDevice>(0);
+        if (mService == null) {
+            return new ArrayList<BluetoothDevice>(0);
+        }
         return mService.getDevicesMatchingConnectionStates(
               new int[] {BluetoothProfile.STATE_CONNECTED,
                          BluetoothProfile.STATE_CONNECTING,
@@ -204,7 +205,7 @@
     }
 
     protected void finalize() {
-        if (V) Log.d(TAG, "finalize()");
+        Log.d(TAG, "finalize()");
         if (mService != null) {
             try {
                 BluetoothAdapter.getDefaultAdapter().closeProfileProxy(BluetoothProfile.MAP,
diff --git a/packages/SystemUI/Android.bp b/packages/SystemUI/Android.bp
new file mode 100644
index 0000000..c9ba268
--- /dev/null
+++ b/packages/SystemUI/Android.bp
@@ -0,0 +1,101 @@
+//
+// 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.
+//
+
+java_library {
+    name: "SystemUI-proto",
+
+    srcs: ["src/**/*.proto"],
+
+    proto: {
+        type: "nano",
+    },
+}
+
+java_library {
+    name: "SystemUI-tags",
+    srcs: ["src/com/android/systemui/EventLogTags.logtags"],
+}
+
+android_library {
+    name: "SystemUI-core",
+    srcs: [
+        "src/**/*.java",
+        "src/**/I*.aidl",
+    ],
+    resource_dirs: [
+        "res-keyguard",
+        "res",
+    ],
+    static_libs: [
+        "SystemUIPluginLib",
+        "SystemUISharedLib",
+        "SettingsLib",
+        "androidx.car_car",
+        "androidx.legacy_legacy-support-v4",
+        "androidx.recyclerview_recyclerview",
+        "androidx.preference_preference",
+        "androidx.appcompat_appcompat",
+        "androidx.mediarouter_mediarouter",
+        "androidx.palette_palette",
+        "androidx.legacy_legacy-preference-v14",
+        "androidx.leanback_leanback",
+        "androidx.slice_slice-core",
+        "androidx.slice_slice-view",
+        "androidx.slice_slice-builders",
+        "androidx.arch.core_core-runtime",
+        "androidx.lifecycle_lifecycle-extensions",
+        "SystemUI-tags",
+        "SystemUI-proto",
+    ],
+    manifest: "AndroidManifest.xml",
+
+    libs: [
+        "telephony-common",
+        "android.car",
+    ],
+
+    aaptflags: [
+        "--extra-packages",
+        "com.android.keyguard",
+    ],
+}
+
+android_app {
+    name: "SystemUI",
+    static_libs: [
+        "SystemUI-core",
+    ],
+
+    platform_apis: true,
+    certificate: "platform",
+    privileged: true,
+
+    optimize: {
+        proguard_flags_files: ["proguard.flags"],
+    },
+
+    libs: [
+        "telephony-common",
+        "android.car",
+    ],
+
+    dxflags: ["--multi-dex"],
+    aaptflags: [
+        "--extra-packages",
+        "com.android.keyguard",
+    ],
+
+}
diff --git a/packages/SystemUI/Android.mk b/packages/SystemUI/Android.mk
deleted file mode 100644
index d9ec0fd0..0000000
--- a/packages/SystemUI/Android.mk
+++ /dev/null
@@ -1,83 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := SystemUI-proto
-
-LOCAL_SRC_FILES := $(call all-proto-files-under,src)
-
-LOCAL_PROTOC_OPTIMIZE_TYPE := nano
-LOCAL_PROTO_JAVA_OUTPUT_PARAMS := optional_field_style=accessors
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := SystemUI-tags
-
-LOCAL_SRC_FILES := src/com/android/systemui/EventLogTags.logtags
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-# ------------------
-
-include $(CLEAR_VARS)
-
-LOCAL_USE_AAPT2 := true
-
-LOCAL_MODULE_TAGS := optional
-
-RELATIVE_FINGERPRINT_PATH := ../../core/java/android/hardware/fingerprint
-
-LOCAL_SRC_FILES := \
-    $(call all-java-files-under, src) \
-    $(call all-Iaidl-files-under, src) \
-    $(call all-Iaidl-files-under, $(RELATIVE_FINGERPRINT_PATH))
-
-LOCAL_STATIC_ANDROID_LIBRARIES := \
-    SystemUIPluginLib \
-    SystemUISharedLib \
-    androidx.car_car \
-    androidx.legacy_legacy-support-v4 \
-    androidx.recyclerview_recyclerview \
-    androidx.preference_preference \
-    androidx.appcompat_appcompat \
-    androidx.mediarouter_mediarouter \
-    androidx.palette_palette \
-    androidx.legacy_legacy-preference-v14 \
-    androidx.leanback_leanback \
-    androidx.slice_slice-core \
-    androidx.slice_slice-view \
-    androidx.slice_slice-builders \
-    androidx.arch.core_core-runtime \
-    androidx.lifecycle_lifecycle-extensions \
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
-    SystemUI-tags \
-    SystemUI-proto
-
-LOCAL_JAVA_LIBRARIES := telephony-common \
-    android.car
-
-LOCAL_PACKAGE_NAME := SystemUI
-LOCAL_PRIVATE_PLATFORM_APIS := true
-LOCAL_CERTIFICATE := platform
-LOCAL_PRIVILEGED_MODULE := true
-
-LOCAL_PROGUARD_FLAG_FILES := proguard.flags
-LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res-keyguard $(LOCAL_PATH)/res
-
-ifneq ($(INCREMENTAL_BUILDS),)
-    LOCAL_PROGUARD_ENABLED := disabled
-    LOCAL_JACK_ENABLED := incremental
-    LOCAL_DX_FLAGS := --multi-dex
-    LOCAL_JACK_FLAGS := --multi-dex native
-endif
-
-include frameworks/base/packages/SettingsLib/common.mk
-
-LOCAL_AAPT_FLAGS := --extra-packages com.android.keyguard
-
-include $(BUILD_PACKAGE)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/packages/SystemUI/plugin/Android.bp b/packages/SystemUI/plugin/Android.bp
new file mode 100644
index 0000000..b38059d
--- /dev/null
+++ b/packages/SystemUI/plugin/Android.bp
@@ -0,0 +1,37 @@
+// Copyright (C) 2016 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_library {
+
+    name: "SystemUIPluginLib",
+
+    srcs: ["src/**/*.java"],
+
+
+}
+
+android_app {
+
+    // Dummy to generate .toc files.
+    name: "PluginDummyLib",
+    platform_apis: true,
+    srcs: ["src/**/*.java"],
+
+    libs: ["SystemUIPluginLib"],
+
+    optimize: {
+        enabled: false,
+    },
+
+}
diff --git a/packages/SystemUI/plugin/Android.mk b/packages/SystemUI/plugin/Android.mk
deleted file mode 100644
index 8634684..0000000
--- a/packages/SystemUI/plugin/Android.mk
+++ /dev/null
@@ -1,42 +0,0 @@
-# Copyright (C) 2016 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_USE_AAPT2 := true
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE := SystemUIPluginLib
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
-LOCAL_JAR_EXCLUDE_FILES := none
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-include $(CLEAR_VARS)
-
-# Dummy to generate .toc files.
-LOCAL_PACKAGE_NAME := PluginDummyLib
-LOCAL_PRIVATE_PLATFORM_APIS := true
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_JAVA_LIBRARIES := SystemUIPluginLib
-
-LOCAL_PROGUARD_ENABLED := disabled
-
-include $(BUILD_PACKAGE)
diff --git a/packages/SystemUI/plugin/ExamplePlugin/Android.bp b/packages/SystemUI/plugin/ExamplePlugin/Android.bp
new file mode 100644
index 0000000..a0eaf14
--- /dev/null
+++ b/packages/SystemUI/plugin/ExamplePlugin/Android.bp
@@ -0,0 +1,14 @@
+android_app {
+
+    name: "ExamplePlugin",
+
+    libs: ["SystemUIPluginLib"],
+
+    certificate: "platform",
+    optimize: {
+        enabled: false,
+    },
+
+    srcs: ["src/**/*.java"],
+
+}
diff --git a/packages/SystemUI/plugin/ExamplePlugin/Android.mk b/packages/SystemUI/plugin/ExamplePlugin/Android.mk
deleted file mode 100644
index 4c82c75..0000000
--- a/packages/SystemUI/plugin/ExamplePlugin/Android.mk
+++ /dev/null
@@ -1,15 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_USE_AAPT2 := true
-
-LOCAL_PACKAGE_NAME := ExamplePlugin
-
-LOCAL_JAVA_LIBRARIES := SystemUIPluginLib
-
-LOCAL_CERTIFICATE := platform
-LOCAL_PROGUARD_ENABLED := disabled
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-include $(BUILD_PACKAGE)
diff --git a/packages/SystemUI/res-keyguard/values/alias.xml b/packages/SystemUI/res-keyguard/values/alias.xml
index f06b450..1c63c79 100644
--- a/packages/SystemUI/res-keyguard/values/alias.xml
+++ b/packages/SystemUI/res-keyguard/values/alias.xml
@@ -25,9 +25,6 @@
     <!-- Alias used to reference framework "OK" string in keyguard.  -->
     <item type="string" name="ok">@*android:string/ok</item>
 
-    <!-- Alias used to reference framework "OK" string in keyguard.  -->
-    <item type="string" name="system_ui_date_pattern">@*android:string/system_ui_date_pattern</item>
-
     <!-- Alias used to reference framework configuration for screen rotation.  -->
     <item type="bool" name="config_enableLockScreenRotation">@*android:bool/config_enableLockScreenRotation</item>
 
diff --git a/packages/SystemUI/res/values-bg/donottranslate.xml b/packages/SystemUI/res/values-bg/donottranslate.xml
deleted file mode 100644
index dcf434d..0000000
--- a/packages/SystemUI/res/values-bg/donottranslate.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/**
- * Copyright (c) 2009, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); 
- * you may not use this file except in compliance with the License. 
- * You may obtain a copy of the License at 
- *
- *     http://www.apache.org/licenses/LICENSE-2.0 
- *
- * Unless required by applicable law or agreed to in writing, software 
- * distributed under the License is distributed on an "AS IS" BASIS, 
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
- * See the License for the specific language governing permissions and 
- * limitations under the License.
- */
--->
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <!-- For formatting day of week and date in DateView.  Day of week precedes date by default,
-         but this may be overridden on a per-locale basis if necessary. -->
-    <string name="status_bar_date_formatter">%2$s\n%1$s</string>
-
-</resources>
diff --git a/packages/SystemUI/res/values-hu/donottranslate.xml b/packages/SystemUI/res/values-hu/donottranslate.xml
deleted file mode 100644
index dcf434d..0000000
--- a/packages/SystemUI/res/values-hu/donottranslate.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/**
- * Copyright (c) 2009, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); 
- * you may not use this file except in compliance with the License. 
- * You may obtain a copy of the License at 
- *
- *     http://www.apache.org/licenses/LICENSE-2.0 
- *
- * Unless required by applicable law or agreed to in writing, software 
- * distributed under the License is distributed on an "AS IS" BASIS, 
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
- * See the License for the specific language governing permissions and 
- * limitations under the License.
- */
--->
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <!-- For formatting day of week and date in DateView.  Day of week precedes date by default,
-         but this may be overridden on a per-locale basis if necessary. -->
-    <string name="status_bar_date_formatter">%2$s\n%1$s</string>
-
-</resources>
diff --git a/packages/SystemUI/res/values-ja/donottranslate.xml b/packages/SystemUI/res/values-ja/donottranslate.xml
deleted file mode 100644
index dcf434d..0000000
--- a/packages/SystemUI/res/values-ja/donottranslate.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/**
- * Copyright (c) 2009, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); 
- * you may not use this file except in compliance with the License. 
- * You may obtain a copy of the License at 
- *
- *     http://www.apache.org/licenses/LICENSE-2.0 
- *
- * Unless required by applicable law or agreed to in writing, software 
- * distributed under the License is distributed on an "AS IS" BASIS, 
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
- * See the License for the specific language governing permissions and 
- * limitations under the License.
- */
--->
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <!-- For formatting day of week and date in DateView.  Day of week precedes date by default,
-         but this may be overridden on a per-locale basis if necessary. -->
-    <string name="status_bar_date_formatter">%2$s\n%1$s</string>
-
-</resources>
diff --git a/packages/SystemUI/res/values-ko/donottranslate.xml b/packages/SystemUI/res/values-ko/donottranslate.xml
deleted file mode 100644
index dcf434d..0000000
--- a/packages/SystemUI/res/values-ko/donottranslate.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/**
- * Copyright (c) 2009, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); 
- * you may not use this file except in compliance with the License. 
- * You may obtain a copy of the License at 
- *
- *     http://www.apache.org/licenses/LICENSE-2.0 
- *
- * Unless required by applicable law or agreed to in writing, software 
- * distributed under the License is distributed on an "AS IS" BASIS, 
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
- * See the License for the specific language governing permissions and 
- * limitations under the License.
- */
--->
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <!-- For formatting day of week and date in DateView.  Day of week precedes date by default,
-         but this may be overridden on a per-locale basis if necessary. -->
-    <string name="status_bar_date_formatter">%2$s\n%1$s</string>
-
-</resources>
diff --git a/packages/SystemUI/res/values-lt/donottranslate.xml b/packages/SystemUI/res/values-lt/donottranslate.xml
deleted file mode 100644
index dcf434d..0000000
--- a/packages/SystemUI/res/values-lt/donottranslate.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/**
- * Copyright (c) 2009, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); 
- * you may not use this file except in compliance with the License. 
- * You may obtain a copy of the License at 
- *
- *     http://www.apache.org/licenses/LICENSE-2.0 
- *
- * Unless required by applicable law or agreed to in writing, software 
- * distributed under the License is distributed on an "AS IS" BASIS, 
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
- * See the License for the specific language governing permissions and 
- * limitations under the License.
- */
--->
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <!-- For formatting day of week and date in DateView.  Day of week precedes date by default,
-         but this may be overridden on a per-locale basis if necessary. -->
-    <string name="status_bar_date_formatter">%2$s\n%1$s</string>
-
-</resources>
diff --git a/packages/SystemUI/res/values-sw720dp/donottranslate.xml b/packages/SystemUI/res/values-sw720dp/donottranslate.xml
deleted file mode 100644
index 0996067..0000000
--- a/packages/SystemUI/res/values-sw720dp/donottranslate.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/**
- * Copyright (c) 2011, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); 
- * you may not use this file except in compliance with the License. 
- * You may obtain a copy of the License at 
- *
- *     http://www.apache.org/licenses/LICENSE-2.0 
- *
- * Unless required by applicable law or agreed to in writing, software 
- * distributed under the License is distributed on an "AS IS" BASIS, 
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
- * See the License for the specific language governing permissions and 
- * limitations under the License.
- */
--->
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <!-- For formatting day of week and date in DateView.  %1$s is DOW, %2$s is date.
-         We show both (DOW on one line, then the date) but this can be overridden for locales as
-         necessary.
-         -->
-    <string name="status_bar_date_formatter">%1$s\n%2$s</string>
-
-</resources>
-
diff --git a/packages/SystemUI/res/values-tr/donottranslate.xml b/packages/SystemUI/res/values-tr/donottranslate.xml
deleted file mode 100644
index dcf434d..0000000
--- a/packages/SystemUI/res/values-tr/donottranslate.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/**
- * Copyright (c) 2009, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); 
- * you may not use this file except in compliance with the License. 
- * You may obtain a copy of the License at 
- *
- *     http://www.apache.org/licenses/LICENSE-2.0 
- *
- * Unless required by applicable law or agreed to in writing, software 
- * distributed under the License is distributed on an "AS IS" BASIS, 
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
- * See the License for the specific language governing permissions and 
- * limitations under the License.
- */
--->
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <!-- For formatting day of week and date in DateView.  Day of week precedes date by default,
-         but this may be overridden on a per-locale basis if necessary. -->
-    <string name="status_bar_date_formatter">%2$s\n%1$s</string>
-
-</resources>
diff --git a/packages/SystemUI/res/values-zh-rCN/donottranslate.xml b/packages/SystemUI/res/values-zh-rCN/donottranslate.xml
deleted file mode 100644
index dcf434d..0000000
--- a/packages/SystemUI/res/values-zh-rCN/donottranslate.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/**
- * Copyright (c) 2009, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); 
- * you may not use this file except in compliance with the License. 
- * You may obtain a copy of the License at 
- *
- *     http://www.apache.org/licenses/LICENSE-2.0 
- *
- * Unless required by applicable law or agreed to in writing, software 
- * distributed under the License is distributed on an "AS IS" BASIS, 
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
- * See the License for the specific language governing permissions and 
- * limitations under the License.
- */
--->
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <!-- For formatting day of week and date in DateView.  Day of week precedes date by default,
-         but this may be overridden on a per-locale basis if necessary. -->
-    <string name="status_bar_date_formatter">%2$s\n%1$s</string>
-
-</resources>
diff --git a/packages/SystemUI/res/values-zh-rTW/donottranslate.xml b/packages/SystemUI/res/values-zh-rTW/donottranslate.xml
deleted file mode 100644
index dcf434d..0000000
--- a/packages/SystemUI/res/values-zh-rTW/donottranslate.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/**
- * Copyright (c) 2009, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); 
- * you may not use this file except in compliance with the License. 
- * You may obtain a copy of the License at 
- *
- *     http://www.apache.org/licenses/LICENSE-2.0 
- *
- * Unless required by applicable law or agreed to in writing, software 
- * distributed under the License is distributed on an "AS IS" BASIS, 
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
- * See the License for the specific language governing permissions and 
- * limitations under the License.
- */
--->
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <!-- For formatting day of week and date in DateView.  Day of week precedes date by default,
-         but this may be overridden on a per-locale basis if necessary. -->
-    <string name="status_bar_date_formatter">%2$s\n%1$s</string>
-
-</resources>
diff --git a/packages/SystemUI/shared/Android.bp b/packages/SystemUI/shared/Android.bp
new file mode 100644
index 0000000..0fb1200
--- /dev/null
+++ b/packages/SystemUI/shared/Android.bp
@@ -0,0 +1,40 @@
+// Copyright (C) 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+android_library {
+
+    name: "SystemUISharedLib",
+    srcs: [
+        "src/**/*.java",
+        "src/**/I*.aidl",
+    ],
+
+}
+
+android_app {
+
+    name: "SysUISharedLib",
+    platform_apis: true,
+    srcs: [
+        "src/**/*.java",
+        "src/**/I*.aidl",
+    ],
+
+    static_libs: ["SystemUISharedLib"],
+
+    optimize: {
+        enabled: false,
+    },
+
+}
diff --git a/packages/SystemUI/shared/Android.mk b/packages/SystemUI/shared/Android.mk
deleted file mode 100644
index f20df0c..0000000
--- a/packages/SystemUI/shared/Android.mk
+++ /dev/null
@@ -1,43 +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_USE_AAPT2 := true
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE := SystemUISharedLib
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src) $(call all-Iaidl-files-under, src)
-
-LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
-LOCAL_JAR_EXCLUDE_FILES := none
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-include $(CLEAR_VARS)
-
-LOCAL_PACKAGE_NAME := SysUISharedLib
-LOCAL_PRIVATE_PLATFORM_APIS := true
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_JAVA_LIBRARIES := SystemUISharedLib
-
-LOCAL_PROGUARD_ENABLED := disabled
-
-include $(BUILD_PACKAGE)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/packages/SystemUI/shared/tests/Android.mk b/packages/SystemUI/shared/tests/Android.mk
index 4e7cbbf..02774c9 100644
--- a/packages/SystemUI/shared/tests/Android.mk
+++ b/packages/SystemUI/shared/tests/Android.mk
@@ -30,10 +30,10 @@
 LOCAL_COMPATIBILITY_SUITE := device-tests
 
 # Add local path sources as well as shared lib sources
-LOCAL_SRC_FILES := $(call all-java-files-under, src) \
-    $(call all-java-files-under, ../src)
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
+	SystemUISharedLib \
     metrics-helper-lib \
     android-support-test \
     mockito-target-inline-minus-junit4 \
diff --git a/packages/SystemUI/src/com/android/systemui/analytics/SensorLoggerSession.java b/packages/SystemUI/src/com/android/systemui/analytics/SensorLoggerSession.java
index f8b73a1..d6472b7 100644
--- a/packages/SystemUI/src/com/android/systemui/analytics/SensorLoggerSession.java
+++ b/packages/SystemUI/src/com/android/systemui/analytics/SensorLoggerSession.java
@@ -101,31 +101,31 @@
 
     public Session toProto() {
         Session proto = new Session();
-        proto.setStartTimestampMillis(mStartTimestampMillis);
-        proto.setDurationMillis(mEndTimestampMillis - mStartTimestampMillis);
-        proto.setBuild(Build.FINGERPRINT);
-        proto.setResult(mResult);
-        proto.setType(mType);
+        proto.startTimestampMillis = mStartTimestampMillis;
+        proto.durationMillis = mEndTimestampMillis - mStartTimestampMillis;
+        proto.build = Build.FINGERPRINT;
+        proto.result = mResult;
+        proto.type = mType;
         proto.sensorEvents = mSensorEvents.toArray(proto.sensorEvents);
         proto.touchEvents = mMotionEvents.toArray(proto.touchEvents);
         proto.phoneEvents = mPhoneEvents.toArray(proto.phoneEvents);
-        proto.setTouchAreaWidth(mTouchAreaWidth);
-        proto.setTouchAreaHeight(mTouchAreaHeight);
+        proto.touchAreaWidth = mTouchAreaWidth;
+        proto.touchAreaHeight = mTouchAreaHeight;
         return proto;
     }
 
     private PhoneEvent phoneEventToProto(int eventType, long sysTimeNanos) {
         PhoneEvent proto = new PhoneEvent();
-        proto.setType(eventType);
-        proto.setTimeOffsetNanos(sysTimeNanos - mStartSystemTimeNanos);
+        proto.type = eventType;
+        proto.timeOffsetNanos = sysTimeNanos - mStartSystemTimeNanos;
         return proto;
     }
 
     private SensorEvent sensorEventToProto(android.hardware.SensorEvent ev, long sysTimeNanos) {
         SensorEvent proto = new SensorEvent();
-        proto.setType(ev.sensor.getType());
-        proto.setTimeOffsetNanos(sysTimeNanos - mStartSystemTimeNanos);
-        proto.setTimestamp(ev.timestamp);
+        proto.type = ev.sensor.getType();
+        proto.timeOffsetNanos = sysTimeNanos - mStartSystemTimeNanos;
+        proto.timestamp = ev.timestamp;
         proto.values = ev.values.clone();
         return proto;
     }
@@ -133,17 +133,17 @@
     private TouchEvent motionEventToProto(MotionEvent ev) {
         int count = ev.getPointerCount();
         TouchEvent proto = new TouchEvent();
-        proto.setTimeOffsetNanos(ev.getEventTimeNano() - mStartSystemTimeNanos);
-        proto.setAction(ev.getActionMasked());
-        proto.setActionIndex(ev.getActionIndex());
+        proto.timeOffsetNanos = ev.getEventTimeNano() - mStartSystemTimeNanos;
+        proto.action = ev.getActionMasked();
+        proto.actionIndex = ev.getActionIndex();
         proto.pointers = new TouchEvent.Pointer[count];
         for (int i = 0; i < count; i++) {
             TouchEvent.Pointer p = new TouchEvent.Pointer();
-            p.setX(ev.getX(i));
-            p.setY(ev.getY(i));
-            p.setSize(ev.getSize(i));
-            p.setPressure(ev.getPressure(i));
-            p.setId(ev.getPointerId(i));
+            p.x = ev.getX(i);
+            p.y = ev.getY(i);
+            p.size = ev.getSize(i);
+            p.pressure = ev.getPressure(i);
+            p.id = ev.getPointerId(i);
             proto.pointers[i] = p;
         }
         return proto;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/PseudoGridView.java b/packages/SystemUI/src/com/android/systemui/qs/PseudoGridView.java
index a1c2577..87c64c7 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/PseudoGridView.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/PseudoGridView.java
@@ -47,16 +47,12 @@
         final int N = a.getIndexCount();
         for (int i = 0; i < N; i++) {
             int attr = a.getIndex(i);
-            switch (attr) {
-                case R.styleable.PseudoGridView_numColumns:
-                    mNumColumns = a.getInt(attr, 3);
-                    break;
-                case R.styleable.PseudoGridView_verticalSpacing:
-                    mVerticalSpacing = a.getDimensionPixelSize(attr, 0);
-                    break;
-                case R.styleable.PseudoGridView_horizontalSpacing:
-                    mHorizontalSpacing = a.getDimensionPixelSize(attr, 0);
-                    break;
+            if (attr == R.styleable.PseudoGridView_numColumns) {
+                mNumColumns = a.getInt(attr, 3);
+            } else if (attr == R.styleable.PseudoGridView_verticalSpacing) {
+                mVerticalSpacing = a.getDimensionPixelSize(attr, 0);
+            } else if (attr == R.styleable.PseudoGridView_horizontalSpacing) {
+                mHorizontalSpacing = a.getDimensionPixelSize(attr, 0);
             }
         }
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/UserDetailItemView.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/UserDetailItemView.java
index 1e9a618..ad7d1b6 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/UserDetailItemView.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/UserDetailItemView.java
@@ -69,13 +69,10 @@
         final int N = a.getIndexCount();
         for (int i = 0; i < N; i++) {
             int attr = a.getIndex(i);
-            switch (attr) {
-                case R.styleable.UserDetailItemView_regularFontFamily:
-                    mRegularTypeface = Typeface.create(a.getString(attr), 0 /* style */);
-                    break;
-                case R.styleable.UserDetailItemView_activatedFontFamily:
-                    mActivatedTypeface = Typeface.create(a.getString(attr), 0 /* style */);
-                    break;
+            if (attr == R.styleable.UserDetailItemView_regularFontFamily) {
+                mRegularTypeface = Typeface.create(a.getString(attr), 0 /* style */);
+            } else if (attr == R.styleable.UserDetailItemView_activatedFontFamily) {
+                mActivatedTypeface = Typeface.create(a.getString(attr), 0 /* style */);
             }
         }
         a.recycle();
diff --git a/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java b/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java
index 3eb3160..98925b9 100644
--- a/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java
+++ b/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java
@@ -226,22 +226,16 @@
         public boolean performAccessibilityAction(View host, int action, Bundle args) {
             int currentPosition = getCurrentPosition();
             SnapTarget nextTarget = null;
-            switch (action) {
-                case R.id.action_move_tl_full:
-                    nextTarget = mSnapAlgorithm.getDismissEndTarget();
-                    break;
-                case R.id.action_move_tl_70:
-                    nextTarget = mSnapAlgorithm.getLastSplitTarget();
-                    break;
-                case R.id.action_move_tl_50:
-                    nextTarget = mSnapAlgorithm.getMiddleTarget();
-                    break;
-                case R.id.action_move_tl_30:
-                    nextTarget = mSnapAlgorithm.getFirstSplitTarget();
-                    break;
-                case R.id.action_move_rb_full:
-                    nextTarget = mSnapAlgorithm.getDismissStartTarget();
-                    break;
+            if (action == R.id.action_move_tl_full) {
+                nextTarget = mSnapAlgorithm.getDismissEndTarget();
+            } else if (action == R.id.action_move_tl_70) {
+                nextTarget = mSnapAlgorithm.getLastSplitTarget();
+            } else if (action == R.id.action_move_tl_50) {
+                nextTarget = mSnapAlgorithm.getMiddleTarget();
+            } else if (action == R.id.action_move_tl_30) {
+                nextTarget = mSnapAlgorithm.getFirstSplitTarget();
+            } else if (action == R.id.action_move_rb_full) {
+                nextTarget = mSnapAlgorithm.getDismissStartTarget();
             }
             if (nextTarget != null) {
                 startDragging(true /* animate */, false /* touching */);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java b/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java
index d647e21..2968722 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java
@@ -2747,16 +2747,18 @@
             case AccessibilityNodeInfo.ACTION_LONG_CLICK:
                 doLongClickCallback();
                 return true;
-            case R.id.action_snooze:
-                NotificationMenuRowPlugin provider = getProvider();
-                if (provider == null) {
-                    provider = createMenu();
+            default:
+                if (action == R.id.action_snooze) {
+                    NotificationMenuRowPlugin provider = getProvider();
+                    if (provider == null) {
+                        provider = createMenu();
+                    }
+                    MenuItem snoozeMenu = provider.getSnoozeMenuItem(getContext());
+                    if (snoozeMenu != null) {
+                        doLongClickCallback(getWidth() / 2, getHeight() / 2, snoozeMenu);
+                    }
+                    return true;
                 }
-                MenuItem snoozeMenu = provider.getSnoozeMenuItem(getContext());
-                if (snoozeMenu != null) {
-                    doLongClickCallback(getWidth() / 2, getHeight() / 2, snoozeMenu);
-                }
-                return true;
         }
         return false;
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
index b136e8a..1177c4f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
@@ -255,13 +255,11 @@
 
         @Override
         public boolean performAccessibilityAction(View host, int action, Bundle args) {
-            switch (action) {
-                case R.id.action_toggle_overview:
-                    SysUiServiceProvider.getComponent(getContext(), Recents.class)
-                            .toggleRecentApps();
-                    break;
-                default:
-                    return super.performAccessibilityAction(host, action, args);
+            if (action == R.id.action_toggle_overview) {
+                SysUiServiceProvider.getComponent(getContext(), Recents.class)
+                        .toggleRecentApps();
+            } else {
+                return super.performAccessibilityAction(host, action, args);
             }
             return true;
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/UserAvatarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/UserAvatarView.java
index dc1b35d..2ed2edb 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/UserAvatarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/UserAvatarView.java
@@ -45,25 +45,18 @@
         final int N = a.getIndexCount();
         for (int i = 0; i < N; i++) {
             int attr = a.getIndex(i);
-            switch (attr) {
-                case R.styleable.UserAvatarView_avatarPadding:
-                    setAvatarPadding(a.getDimension(attr, 0));
-                    break;
-                case R.styleable.UserAvatarView_frameWidth:
-                    setFrameWidth(a.getDimension(attr, 0));
-                    break;
-                case R.styleable.UserAvatarView_framePadding:
-                    setFramePadding(a.getDimension(attr, 0));
-                    break;
-                case R.styleable.UserAvatarView_frameColor:
-                    setFrameColor(a.getColorStateList(attr));
-                    break;
-                case R.styleable.UserAvatarView_badgeDiameter:
-                    setBadgeDiameter(a.getDimension(attr, 0));
-                    break;
-                case R.styleable.UserAvatarView_badgeMargin:
-                    setBadgeMargin(a.getDimension(attr, 0));
-                    break;
+            if (attr == R.styleable.UserAvatarView_avatarPadding) {
+                setAvatarPadding(a.getDimension(attr, 0));
+            } else if (attr == R.styleable.UserAvatarView_frameWidth) {
+                setFrameWidth(a.getDimension(attr, 0));
+            } else if (attr == R.styleable.UserAvatarView_framePadding) {
+                setFramePadding(a.getDimension(attr, 0));
+            } else if (attr == R.styleable.UserAvatarView_frameColor) {
+                setFrameColor(a.getColorStateList(attr));
+            } else if (attr == R.styleable.UserAvatarView_badgeDiameter) {
+                setBadgeDiameter(a.getDimension(attr, 0));
+            } else if (attr == R.styleable.UserAvatarView_badgeMargin) {
+                setBadgeMargin(a.getDimension(attr, 0));
             }
         }
         a.recycle();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java
index 924aa01..d43dc81 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java
@@ -127,19 +127,14 @@
         final int length = arr.getIndexCount();
         for (int i = 0; i < length; i++) {
             int attr = arr.getIndex(i);
-            switch (attr) {
-                case R.styleable.SmartReplyView_spacing:
-                    spacing = arr.getDimensionPixelSize(i, 0);
-                    break;
-                case R.styleable.SmartReplyView_singleLineButtonPaddingHorizontal:
-                    singleLineButtonPaddingHorizontal = arr.getDimensionPixelSize(i, 0);
-                    break;
-                case R.styleable.SmartReplyView_doubleLineButtonPaddingHorizontal:
-                    doubleLineButtonPaddingHorizontal = arr.getDimensionPixelSize(i, 0);
-                    break;
-                case R.styleable.SmartReplyView_buttonStrokeWidth:
-                    strokeWidth = arr.getDimensionPixelSize(i, 0);
-                    break;
+            if (attr == R.styleable.SmartReplyView_spacing) {
+                spacing = arr.getDimensionPixelSize(i, 0);
+            } else if (attr == R.styleable.SmartReplyView_singleLineButtonPaddingHorizontal) {
+                singleLineButtonPaddingHorizontal = arr.getDimensionPixelSize(i, 0);
+            } else if (attr == R.styleable.SmartReplyView_doubleLineButtonPaddingHorizontal) {
+                doubleLineButtonPaddingHorizontal = arr.getDimensionPixelSize(i, 0);
+            } else if (attr == R.styleable.SmartReplyView_buttonStrokeWidth) {
+                strokeWidth = arr.getDimensionPixelSize(i, 0);
             }
         }
         arr.recycle();
diff --git a/packages/SystemUI/tests/Android.mk b/packages/SystemUI/tests/Android.mk
index a4120c4..9ee5532 100644
--- a/packages/SystemUI/tests/Android.mk
+++ b/packages/SystemUI/tests/Android.mk
@@ -30,37 +30,17 @@
 LOCAL_COMPATIBILITY_SUITE := device-tests
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src) \
-    $(call all-Iaidl-files-under, src) \
-    $(call all-java-files-under, ../src)
+    $(call all-Iaidl-files-under, src)
 
-LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res \
-    frameworks/base/packages/SystemUI/res \
-    frameworks/base/packages/SystemUI/res-keyguard \
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
 
 LOCAL_STATIC_ANDROID_LIBRARIES := \
-    SystemUIPluginLib \
-    SystemUISharedLib \
-    androidx.car_car \
-    androidx.legacy_legacy-support-v4 \
-    androidx.recyclerview_recyclerview \
-    androidx.preference_preference \
-    androidx.appcompat_appcompat \
-    androidx.mediarouter_mediarouter \
-    androidx.palette_palette \
-    androidx.legacy_legacy-preference-v14 \
-    androidx.leanback_leanback \
-    androidx.slice_slice-core \
-    androidx.slice_slice-view \
-    androidx.slice_slice-builders \
-    androidx.arch.core_core-runtime \
-    androidx.lifecycle_lifecycle-extensions \
+    SystemUI-core
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     metrics-helper-lib \
     android-support-test \
     mockito-target-inline-minus-junit4 \
-    SystemUI-proto \
-    SystemUI-tags \
     testables \
     truth-prebuilt \
 
@@ -70,7 +50,6 @@
     libdexmakerjvmtiagent \
     libmultiplejvmtiagentsinterferenceagent
 
-
 LOCAL_JAVA_LIBRARIES := \
     android.test.runner \
     telephony-common \
@@ -112,8 +91,6 @@
 LOCAL_JACK_COVERAGE_INCLUDE_FILTER := com.android.systemui.*
 LOCAL_JACK_COVERAGE_EXCLUDE_FILTER := com.android.systemui.tests.*,$(jacoco_exclude)
 
-include frameworks/base/packages/SettingsLib/common.mk
-
 ifeq ($(EXCLUDE_SYSTEMUI_TESTS),)
     include $(BUILD_PACKAGE)
 endif
diff --git a/packages/SystemUI/tests/AndroidManifest.xml b/packages/SystemUI/tests/AndroidManifest.xml
index 1be8322..5395dff 100644
--- a/packages/SystemUI/tests/AndroidManifest.xml
+++ b/packages/SystemUI/tests/AndroidManifest.xml
@@ -15,6 +15,8 @@
 -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:androidprv="http://schemas.android.com/apk/prv/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
     package="com.android.systemui.tests">
 
     <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
@@ -63,6 +65,26 @@
                 <action android:name="com.android.systemui.action.TEST_ACTION" />
             </intent-filter>
         </receiver>
+
+        <provider
+            android:name="androidx.lifecycle.ProcessLifecycleOwnerInitializer"
+            tools:replace="android:authorities"
+            android:authorities="${applicationId}.lifecycle-tests"
+            android:exported="false"
+            android:multiprocess="true" />
+
+        <provider android:name="com.android.systemui.keyguard.KeyguardSliceProvider"
+            android:authorities="com.android.systemui.test.keyguard.disabled"
+            android:enabled="false"
+            tools:replace="android:authorities"
+            tools:node="remove" />
+
+        <provider
+            android:name="androidx.core.content.FileProvider"
+            android:authorities="com.android.systemui.test.fileprovider"
+            android:exported="false"
+            tools:replace="android:authorities"
+            android:grantUriPermissions="true" />
     </application>
 
     <instrumentation android:name="android.testing.TestableInstrumentation"
diff --git a/services/core/java/com/android/server/NetworkManagementService.java b/services/core/java/com/android/server/NetworkManagementService.java
index bd0a4c7..c79cf71 100644
--- a/services/core/java/com/android/server/NetworkManagementService.java
+++ b/services/core/java/com/android/server/NetworkManagementService.java
@@ -315,7 +315,6 @@
     }
     private HashMap<String, IdleTimerParams> mActiveIdleTimers = Maps.newHashMap();
 
-    private volatile boolean mBandwidthControlEnabled;
     private volatile boolean mFirewallEnabled;
     private volatile boolean mStrictEnabled;
 
@@ -619,27 +618,11 @@
      */
     private void prepareNativeDaemon() {
 
-        mBandwidthControlEnabled = false;
-
-        // only enable bandwidth control when support exists
-        final boolean hasKernelSupport = new File("/proc/net/xt_qtaguid/ctrl").exists();
-
         // push any existing quota or UID rules
         synchronized (mQuotaLock) {
 
-            if (hasKernelSupport) {
-                Slog.d(TAG, "enabling bandwidth control");
-                try {
-                    mConnector.execute("bandwidth", "enable");
-                    mBandwidthControlEnabled = true;
-                } catch (NativeDaemonConnectorException e) {
-                    Log.wtf(TAG, "problem enabling bandwidth controls", e);
-                }
-            } else {
-                Slog.i(TAG, "not enabling bandwidth control");
-            }
-
-            SystemProperties.set(PROP_QTAGUID_ENABLED, mBandwidthControlEnabled ? "1" : "0");
+            // Netd unconditionally enable bandwidth control
+            SystemProperties.set(PROP_QTAGUID_ENABLED, "1");
 
             mStrictEnabled = true;
 
@@ -721,11 +704,10 @@
             }
         }
 
-        if (mBandwidthControlEnabled) {
-            try {
-                getBatteryStats().noteNetworkStatsEnabled();
-            } catch (RemoteException e) {
-            }
+
+        try {
+            getBatteryStats().noteNetworkStatsEnabled();
+        } catch (RemoteException e) {
         }
 
     }
@@ -1571,10 +1553,6 @@
     public void setInterfaceQuota(String iface, long quotaBytes) {
         mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
 
-        // silently discard when control disabled
-        // TODO: eventually migrate to be always enabled
-        if (!mBandwidthControlEnabled) return;
-
         synchronized (mQuotaLock) {
             if (mActiveQuotas.containsKey(iface)) {
                 throw new IllegalStateException("iface " + iface + " already has quota");
@@ -1605,10 +1583,6 @@
     public void removeInterfaceQuota(String iface) {
         mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
 
-        // silently discard when control disabled
-        // TODO: eventually migrate to be always enabled
-        if (!mBandwidthControlEnabled) return;
-
         synchronized (mQuotaLock) {
             if (!mActiveQuotas.containsKey(iface)) {
                 // TODO: eventually consider throwing
@@ -1642,10 +1616,6 @@
     public void setInterfaceAlert(String iface, long alertBytes) {
         mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
 
-        // silently discard when control disabled
-        // TODO: eventually migrate to be always enabled
-        if (!mBandwidthControlEnabled) return;
-
         // quick sanity check
         if (!mActiveQuotas.containsKey(iface)) {
             throw new IllegalStateException("setting alert requires existing quota on iface");
@@ -1670,10 +1640,6 @@
     public void removeInterfaceAlert(String iface) {
         mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
 
-        // silently discard when control disabled
-        // TODO: eventually migrate to be always enabled
-        if (!mBandwidthControlEnabled) return;
-
         synchronized (mQuotaLock) {
             if (!mActiveAlerts.containsKey(iface)) {
                 // TODO: eventually consider throwing
@@ -1694,10 +1660,6 @@
     public void setGlobalAlert(long alertBytes) {
         mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
 
-        // silently discard when control disabled
-        // TODO: eventually migrate to be always enabled
-        if (!mBandwidthControlEnabled) return;
-
         try {
             mConnector.execute("bandwidth", "setglobalalert", alertBytes);
         } catch (NativeDaemonConnectorException e) {
@@ -1708,10 +1670,6 @@
     private void setUidOnMeteredNetworkList(int uid, boolean blacklist, boolean enable) {
         mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
 
-        // silently discard when control disabled
-        // TODO: eventually migrate to be always enabled
-        if (!mBandwidthControlEnabled) return;
-
         final String chain = blacklist ? "naughtyapps" : "niceapps";
         final String suffix = enable ? "add" : "remove";
 
@@ -1863,7 +1821,7 @@
     @Override
     public boolean isBandwidthControlEnabled() {
         mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
-        return mBandwidthControlEnabled;
+        return true;
     }
 
     @Override
@@ -2370,7 +2328,6 @@
         mConnector.dump(fd, pw, args);
         pw.println();
 
-        pw.print("Bandwidth control enabled: "); pw.println(mBandwidthControlEnabled);
         pw.print("mMobileActivityFromRadio="); pw.print(mMobileActivityFromRadio);
                 pw.print(" mLastPowerStateFromRadio="); pw.println(mLastPowerStateFromRadio);
         pw.print("mNetworkActive="); pw.println(mNetworkActive);
diff --git a/services/core/java/com/android/server/TelephonyRegistry.java b/services/core/java/com/android/server/TelephonyRegistry.java
index 566ce4f..0955bed 100644
--- a/services/core/java/com/android/server/TelephonyRegistry.java
+++ b/services/core/java/com/android/server/TelephonyRegistry.java
@@ -99,6 +99,7 @@
 
         IPhoneStateListener callback;
         IOnSubscriptionsChangedListener onSubscriptionsChangedListenerCallback;
+        IOnSubscriptionsChangedListener onOpportunisticSubscriptionsChangedListenerCallback;
 
         int callerUid;
         int callerPid;
@@ -117,6 +118,10 @@
             return (onSubscriptionsChangedListenerCallback != null);
         }
 
+        boolean matchOnOpportunisticSubscriptionsChangedListener() {
+            return (onOpportunisticSubscriptionsChangedListenerCallback != null);
+        }
+
         boolean canReadCallLog() {
             try {
                 return TelephonyPermissions.checkReadCallLog(
@@ -131,7 +136,9 @@
             return "{callingPackage=" + callingPackage + " binder=" + binder
                     + " callback=" + callback
                     + " onSubscriptionsChangedListenererCallback="
-                                            + onSubscriptionsChangedListenerCallback
+                    + onSubscriptionsChangedListenerCallback
+                    + " onOpportunisticSubscriptionsChangedListenererCallback="
+                    + onOpportunisticSubscriptionsChangedListenerCallback
                     + " callerUid=" + callerUid + " subId=" + subId + " phoneId=" + phoneId
                     + " events=" + Integer.toHexString(events) + "}";
         }
@@ -147,7 +154,9 @@
 
     private final AppOpsManager mAppOps;
 
-    private boolean hasNotifySubscriptionInfoChangedOccurred = false;
+    private boolean mHasNotifySubscriptionInfoChangedOccurred = false;
+
+    private boolean mHasNotifyOpportunisticSubscriptionInfoChangedOccurred = false;
 
     private int mNumPhones;
 
@@ -407,7 +416,7 @@
                 log("listen oscl:  Register r=" + r);
             }
             // Always notify when registration occurs if there has been a notification.
-            if (hasNotifySubscriptionInfoChangedOccurred) {
+            if (mHasNotifySubscriptionInfoChangedOccurred) {
                 try {
                     if (VDBG) log("listen oscl: send to r=" + r);
                     r.onSubscriptionsChangedListenerCallback.onSubscriptionsChanged();
@@ -417,7 +426,7 @@
                     remove(r.binder);
                 }
             } else {
-                log("listen oscl: hasNotifySubscriptionInfoChangedOccurred==false no callback");
+                log("listen oscl: mHasNotifySubscriptionInfoChangedOccurred==false no callback");
             }
         }
     }
@@ -429,15 +438,61 @@
         remove(callback.asBinder());
     }
 
+
+    @Override
+    public void addOnOpportunisticSubscriptionsChangedListener(String callingPackage,
+            IOnSubscriptionsChangedListener callback) {
+        int callerUserId = UserHandle.getCallingUserId();
+        mAppOps.checkPackage(Binder.getCallingUid(), callingPackage);
+        if (VDBG) {
+            log("listen ooscl: E pkg=" + callingPackage + " myUserId=" + UserHandle.myUserId()
+                    + " callerUserId="  + callerUserId + " callback=" + callback
+                    + " callback.asBinder=" + callback.asBinder());
+        }
+
+        synchronized (mRecords) {
+            // register
+            IBinder b = callback.asBinder();
+            Record r = add(b);
+
+            if (r == null) {
+                return;
+            }
+
+            r.context = mContext;
+            r.onOpportunisticSubscriptionsChangedListenerCallback = callback;
+            r.callingPackage = callingPackage;
+            r.callerUid = Binder.getCallingUid();
+            r.callerPid = Binder.getCallingPid();
+            r.events = 0;
+            if (DBG) {
+                log("listen ooscl:  Register r=" + r);
+            }
+            // Always notify when registration occurs if there has been a notification.
+            if (mHasNotifyOpportunisticSubscriptionInfoChangedOccurred) {
+                try {
+                    if (VDBG) log("listen ooscl: send to r=" + r);
+                    r.onOpportunisticSubscriptionsChangedListenerCallback.onSubscriptionsChanged();
+                    if (VDBG) log("listen ooscl: sent to r=" + r);
+                } catch (RemoteException e) {
+                    if (VDBG) log("listen ooscl: remote exception sending to r=" + r + " e=" + e);
+                    remove(r.binder);
+                }
+            } else {
+                log("listen ooscl: hasNotifyOpptSubInfoChangedOccurred==false no callback");
+            }
+        }
+    }
+
     @Override
     public void notifySubscriptionInfoChanged() {
         if (VDBG) log("notifySubscriptionInfoChanged:");
         synchronized (mRecords) {
-            if (!hasNotifySubscriptionInfoChangedOccurred) {
+            if (!mHasNotifySubscriptionInfoChangedOccurred) {
                 log("notifySubscriptionInfoChanged: first invocation mRecords.size="
                         + mRecords.size());
             }
-            hasNotifySubscriptionInfoChangedOccurred = true;
+            mHasNotifySubscriptionInfoChangedOccurred = true;
             mRemoveList.clear();
             for (Record r : mRecords) {
                 if (r.matchOnSubscriptionsChangedListener()) {
@@ -456,6 +511,33 @@
     }
 
     @Override
+    public void notifyOpportunisticSubscriptionInfoChanged() {
+        if (VDBG) log("notifyOpptSubscriptionInfoChanged:");
+        synchronized (mRecords) {
+            if (!mHasNotifyOpportunisticSubscriptionInfoChangedOccurred) {
+                log("notifyOpptSubscriptionInfoChanged: first invocation mRecords.size="
+                        + mRecords.size());
+            }
+            mHasNotifyOpportunisticSubscriptionInfoChangedOccurred = true;
+            mRemoveList.clear();
+            for (Record r : mRecords) {
+                if (r.matchOnOpportunisticSubscriptionsChangedListener()) {
+                    try {
+                        if (VDBG) log("notifyOpptSubChanged: call oosc to r=" + r);
+                        r.onOpportunisticSubscriptionsChangedListenerCallback
+                                .onSubscriptionsChanged();
+                        if (VDBG) log("notifyOpptSubChanged: done oosc to r=" + r);
+                    } catch (RemoteException ex) {
+                        if (VDBG) log("notifyOpptSubChanged: RemoteException r=" + r);
+                        mRemoveList.add(r.binder);
+                    }
+                }
+            }
+            handleRemoveListLocked();
+        }
+    }
+
+    @Override
     public void listen(String pkgForDebug, IPhoneStateListener callback, int events,
             boolean notifyNow) {
         listenForSubscriber(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID, pkgForDebug, callback,
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 2447a03..9d0a865 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -5886,6 +5886,7 @@
     private final void handleAppDiedLocked(ProcessRecord app,
             boolean restarting, boolean allowRestart) {
         int pid = app.pid;
+        final boolean clearLaunchStartTime = !restarting && app.removed && app.foregroundActivities;
         boolean kept = cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1,
                 false /*replacingPid*/);
         if (!kept && !restarting) {
@@ -5926,6 +5927,19 @@
         } finally {
             mWindowManager.continueSurfaceLayout();
         }
+
+        // TODO (b/67683350)
+        // When an app process is removed, activities from the process may be relaunched. In the
+        // case of forceStopPackageLocked the activities are finished before any window is drawn,
+        // and the launch time is not cleared. This will be incorrectly used to calculate launch
+        // time for the next launched activity launched in the same windowing mode.
+        if (clearLaunchStartTime) {
+            final LaunchTimeTracker.Entry entry = mStackSupervisor
+                    .getLaunchTimeTracker().getEntry(mStackSupervisor.getWindowingMode());
+            if (entry != null) {
+                entry.mLaunchStartTime = 0;
+            }
+        }
     }
 
     private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
@@ -21996,7 +22010,7 @@
             activeInstr.mUiAutomationConnection = uiAutomationConnection;
             activeInstr.mResultClass = className;
 
-            boolean disableHiddenApiChecks = ai.usesNonSdkApi
+            boolean disableHiddenApiChecks = ai.usesNonSdkApi()
                     || (flags & INSTRUMENTATION_FLAG_DISABLE_HIDDEN_API_CHECKS) != 0;
             if (disableHiddenApiChecks) {
                 enforceCallingPermission(android.Manifest.permission.DISABLE_HIDDEN_API_CHECKS,
diff --git a/services/core/java/com/android/server/pm/OtaDexoptService.java b/services/core/java/com/android/server/pm/OtaDexoptService.java
index 320affb..748cf08 100644
--- a/services/core/java/com/android/server/pm/OtaDexoptService.java
+++ b/services/core/java/com/android/server/pm/OtaDexoptService.java
@@ -40,6 +40,7 @@
 import java.io.FileDescriptor;
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Collections;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
 
@@ -124,7 +125,8 @@
         synchronized (mPackageManagerService.mPackages) {
             // Important: the packages we need to run with ab-ota compiler-reason.
             important = PackageManagerServiceUtils.getPackagesForDexopt(
-                    mPackageManagerService.mPackages.values(), mPackageManagerService);
+                    mPackageManagerService.mPackages.values(), mPackageManagerService,
+                    DEBUG_DEXOPT);
             // Others: we should optimize this with the (first-)boot compiler-reason.
             others = new ArrayList<>(mPackageManagerService.mPackages.values());
             others.removeAll(important);
@@ -157,6 +159,24 @@
         long spaceAvailableNow = getAvailableSpace();
 
         prepareMetricsLogging(important.size(), others.size(), spaceAvailable, spaceAvailableNow);
+
+        if (DEBUG_DEXOPT) {
+            try {
+                // Output some data about the packages.
+                PackageParser.Package lastUsed = Collections.max(important,
+                        (pkg1, pkg2) -> Long.compare(
+                                pkg1.getLatestForegroundPackageUseTimeInMills(),
+                                pkg2.getLatestForegroundPackageUseTimeInMills()));
+                Log.d(TAG, "A/B OTA: lastUsed time = "
+                        + lastUsed.getLatestForegroundPackageUseTimeInMills());
+                Log.d(TAG, "A/B OTA: deprioritized packages:");
+                for (PackageParser.Package pkg : others) {
+                    Log.d(TAG, "  " + pkg.packageName + " - "
+                            + pkg.getLatestForegroundPackageUseTimeInMills());
+                }
+            } catch (Exception ignored) {
+            }
+        }
     }
 
     @Override
diff --git a/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java b/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
index 1aea8f0..390c0cc 100644
--- a/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
+++ b/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
@@ -164,6 +164,13 @@
     public static List<PackageParser.Package> getPackagesForDexopt(
             Collection<PackageParser.Package> packages,
             PackageManagerService packageManagerService) {
+        return getPackagesForDexopt(packages, packageManagerService, DEBUG_DEXOPT);
+    }
+
+    public static List<PackageParser.Package> getPackagesForDexopt(
+            Collection<PackageParser.Package> packages,
+            PackageManagerService packageManagerService,
+            boolean debug) {
         ArrayList<PackageParser.Package> remainingPkgs = new ArrayList<>(packages);
         LinkedList<PackageParser.Package> result = new LinkedList<>();
         ArrayList<PackageParser.Package> sortTemp = new ArrayList<>(remainingPkgs.size());
@@ -189,14 +196,14 @@
         // TODO: add a property to control this?
         Predicate<PackageParser.Package> remainingPredicate;
         if (!remainingPkgs.isEmpty() && packageManagerService.isHistoricalPackageUsageAvailable()) {
-            if (DEBUG_DEXOPT) {
+            if (debug) {
                 Log.i(TAG, "Looking at historical package use");
             }
             // Get the package that was used last.
             PackageParser.Package lastUsed = Collections.max(remainingPkgs, (pkg1, pkg2) ->
                     Long.compare(pkg1.getLatestForegroundPackageUseTimeInMills(),
                             pkg2.getLatestForegroundPackageUseTimeInMills()));
-            if (DEBUG_DEXOPT) {
+            if (debug) {
                 Log.i(TAG, "Taking package " + lastUsed.packageName + " as reference in time use");
             }
             long estimatedPreviousSystemUseTime =
@@ -218,7 +225,7 @@
         applyPackageFilter(remainingPredicate, result, remainingPkgs, sortTemp,
                 packageManagerService);
 
-        if (DEBUG_DEXOPT) {
+        if (debug) {
             Log.i(TAG, "Packages to be dexopted: " + packagesToString(result));
             Log.i(TAG, "Packages skipped from dexopt: " + packagesToString(remainingPkgs));
         }
diff --git a/services/net/java/android/net/ip/IpClient.java b/services/net/java/android/net/ip/IpClient.java
index 3cdef1e..ccc092d 100644
--- a/services/net/java/android/net/ip/IpClient.java
+++ b/services/net/java/android/net/ip/IpClient.java
@@ -1385,6 +1385,20 @@
 
     private boolean startIpReachabilityMonitor() {
         try {
+            // TODO: Fetch these parameters from settings, and install a
+            // settings observer to watch for update and re-program these
+            // parameters (Q: is this level of dynamic updatability really
+            // necessary or does reading from settings at startup suffice?).
+            final int NUM_SOLICITS = 5;
+            final int INTER_SOLICIT_INTERVAL_MS = 750;
+            setNeighborParameters(mDependencies.getNetd(), mInterfaceName,
+                    NUM_SOLICITS, INTER_SOLICIT_INTERVAL_MS);
+        } catch (Exception e) {
+            mLog.e("Failed to adjust neighbor parameters", e);
+            // Carry on using the system defaults (currently: 3, 1000);
+        }
+
+        try {
             mIpReachabilityMonitor = new IpReachabilityMonitor(
                     mContext,
                     mInterfaceParams,
@@ -1863,6 +1877,20 @@
         }
     }
 
+    private static void setNeighborParameters(
+            INetd netd, String ifName, int num_solicits, int inter_solicit_interval_ms)
+            throws RemoteException, IllegalArgumentException {
+        Preconditions.checkNotNull(netd);
+        Preconditions.checkArgument(!TextUtils.isEmpty(ifName));
+        Preconditions.checkArgument(num_solicits > 0);
+        Preconditions.checkArgument(inter_solicit_interval_ms > 0);
+
+        for (int family : new Integer[]{INetd.IPV4, INetd.IPV6}) {
+            netd.setProcSysNet(family, INetd.NEIGH, ifName, "retrans_time_ms", Integer.toString(inter_solicit_interval_ms));
+            netd.setProcSysNet(family, INetd.NEIGH, ifName, "ucast_solicit", Integer.toString(num_solicits));
+        }
+    }
+
     // TODO: extract out into CollectionUtils.
     static <T> boolean any(Iterable<T> coll, Predicate<T> fn) {
         for (T t : coll) {
diff --git a/services/net/java/android/net/ip/RouterAdvertisementDaemon.java b/services/net/java/android/net/ip/RouterAdvertisementDaemon.java
index 8fbc01e..9d686ef 100644
--- a/services/net/java/android/net/ip/RouterAdvertisementDaemon.java
+++ b/services/net/java/android/net/ip/RouterAdvertisementDaemon.java
@@ -119,13 +119,23 @@
     private volatile UnicastResponder mUnicastResponder;
 
     public static class RaParams {
+        // Tethered traffic will have the hop limit properly decremented.
+        // Consequently, set the hoplimit greater by one than the upstream
+        // unicast hop limit.
+        //
+        // TODO: Dynamically pass down the IPV6_UNICAST_HOPS value from the
+        // upstream interface for more correct behaviour.
+        static final byte DEFAULT_HOPLIMIT = 65;
+
         public boolean hasDefaultRoute;
+        public byte hopLimit;
         public int mtu;
         public HashSet<IpPrefix> prefixes;
         public HashSet<Inet6Address> dnses;
 
         public RaParams() {
             hasDefaultRoute = false;
+            hopLimit = DEFAULT_HOPLIMIT;
             mtu = IPV6_MIN_MTU;
             prefixes = new HashSet<IpPrefix>();
             dnses = new HashSet<Inet6Address>();
@@ -133,6 +143,7 @@
 
         public RaParams(RaParams other) {
             hasDefaultRoute = other.hasDefaultRoute;
+            hopLimit = other.hopLimit;
             mtu = other.mtu;
             prefixes = (HashSet) other.prefixes.clone();
             dnses = (HashSet) other.dnses.clone();
@@ -273,10 +284,12 @@
         final ByteBuffer ra = ByteBuffer.wrap(mRA);
         ra.order(ByteOrder.BIG_ENDIAN);
 
+        final boolean haveRaParams = (mRaParams != null);
         boolean shouldSendRA = false;
 
         try {
-            putHeader(ra, mRaParams != null && mRaParams.hasDefaultRoute);
+            putHeader(ra, haveRaParams && mRaParams.hasDefaultRoute,
+                    haveRaParams ? mRaParams.hopLimit : RaParams.DEFAULT_HOPLIMIT);
             putSlla(ra, mInterface.macAddr.toByteArray());
             mRaLength = ra.position();
 
@@ -287,7 +300,7 @@
             //
             // putExpandedFlagsOption(ra);
 
-            if (mRaParams != null) {
+            if (haveRaParams) {
                 putMtu(ra, mRaParams.mtu);
                 mRaLength = ra.position();
 
@@ -348,7 +361,7 @@
     private static byte asByte(int value) { return (byte) value; }
     private static short asShort(int value) { return (short) value; }
 
-    private static void putHeader(ByteBuffer ra, boolean hasDefaultRoute) {
+    private static void putHeader(ByteBuffer ra, boolean hasDefaultRoute, byte hopLimit) {
         /**
             Router Advertisement Message Format
 
@@ -366,11 +379,10 @@
             |   Options ...
             +-+-+-+-+-+-+-+-+-+-+-+-
         */
-        final byte DEFAULT_HOPLIMIT = 64;
         ra.put(ICMPV6_ND_ROUTER_ADVERT)
           .put(asByte(0))
           .putShort(asShort(0))
-          .put(DEFAULT_HOPLIMIT)
+          .put(hopLimit)
           // RFC 4191 "high" preference, iff. advertising a default route.
           .put(hasDefaultRoute ? asByte(0x08) : asByte(0))
           .putShort(hasDefaultRoute ? asShort(DEFAULT_LIFETIME) : asShort(0))
diff --git a/telephony/java/android/telephony/SubscriptionManager.java b/telephony/java/android/telephony/SubscriptionManager.java
index 119733e..f7c8e0e 100644
--- a/telephony/java/android/telephony/SubscriptionManager.java
+++ b/telephony/java/android/telephony/SubscriptionManager.java
@@ -19,6 +19,7 @@
 import static android.net.NetworkPolicyManager.OVERRIDE_CONGESTED;
 import static android.net.NetworkPolicyManager.OVERRIDE_UNMETERED;
 
+import android.annotation.CallbackExecutor;
 import android.annotation.DurationMillisLong;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
@@ -47,6 +48,7 @@
 import android.os.ServiceManager;
 import android.telephony.euicc.EuiccManager;
 import android.util.DisplayMetrics;
+import android.util.Log;
 
 import com.android.internal.telephony.IOnSubscriptionsChangedListener;
 import com.android.internal.telephony.ISub;
@@ -57,6 +59,7 @@
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
+import java.util.concurrent.Executor;
 import java.util.concurrent.TimeUnit;
 
 /**
@@ -666,7 +669,7 @@
                 tr.addOnSubscriptionsChangedListener(pkgName, listener.callback);
             }
         } catch (RemoteException ex) {
-            // Should not happen
+            Log.e(LOG_TAG, "Remote exception ITelephonyRegistry " + ex);
         }
     }
 
@@ -684,7 +687,7 @@
                     + " listener=" + listener);
         }
         try {
-            // We use the TelephonyRegistry as its runs in the system and thus is always
+            // We use the TelephonyRegistry as it runs in the system and thus is always
             // available where as SubscriptionController could crash and not be available
             ITelephonyRegistry tr = ITelephonyRegistry.Stub.asInterface(ServiceManager.getService(
                     "telephony.registry"));
@@ -692,7 +695,116 @@
                 tr.removeOnSubscriptionsChangedListener(pkgForDebug, listener.callback);
             }
         } catch (RemoteException ex) {
-            // Should not happen
+            Log.e(LOG_TAG, "Remote exception ITelephonyRegistry " + ex);
+        }
+    }
+
+    /**
+     * A listener class for monitoring changes to {@link SubscriptionInfo} records of opportunistic
+     * subscriptions.
+     * <p>
+     * Override the onOpportunisticSubscriptionsChanged method in the object that extends this
+     * or {@link #addOnOpportunisticSubscriptionsChangedListener(
+     * Executor, OnOpportunisticSubscriptionsChangedListener)}
+     * to register your listener and to unregister invoke
+     * {@link #removeOnOpportunisticSubscriptionsChangedListener(
+     * OnOpportunisticSubscriptionsChangedListener)}
+     * <p>
+     * Permissions android.Manifest.permission.READ_PHONE_STATE is required
+     * for #onOpportunisticSubscriptionsChanged to be invoked.
+     */
+    public static class OnOpportunisticSubscriptionsChangedListener {
+        private Executor mExecutor;
+        /**
+         * Callback invoked when there is any change to any SubscriptionInfo. Typically
+         * this method would invoke {@link #getActiveSubscriptionInfoList}
+         */
+        public void onOpportunisticSubscriptionsChanged() {
+            if (DBG) log("onOpportunisticSubscriptionsChanged: NOT OVERRIDDEN");
+        }
+
+        private void setExecutor(Executor executor) {
+            mExecutor = executor;
+        }
+
+        /**
+         * The callback methods need to be called on the handler thread where
+         * this object was created.  If the binder did that for us it'd be nice.
+         */
+        IOnSubscriptionsChangedListener callback = new IOnSubscriptionsChangedListener.Stub() {
+            @Override
+            public void onSubscriptionsChanged() {
+                if (DBG) log("onOpportunisticSubscriptionsChanged callback received.");
+                mExecutor.execute(() -> onOpportunisticSubscriptionsChanged());
+            }
+        };
+
+        private void log(String s) {
+            Rlog.d(LOG_TAG, s);
+        }
+    }
+
+    /**
+     * Register for changes to the list of opportunistic subscription records or to the
+     * individual records themselves. When a change occurs the onOpportunisticSubscriptionsChanged
+     * method of the listener will be invoked immediately if there has been a notification.
+     *
+     * @param listener an instance of {@link OnOpportunisticSubscriptionsChangedListener} with
+     *                 onOpportunisticSubscriptionsChanged overridden.
+     */
+    public void addOnOpportunisticSubscriptionsChangedListener(
+            @NonNull @CallbackExecutor Executor executor,
+            @NonNull OnOpportunisticSubscriptionsChangedListener listener) {
+        if (executor == null || listener == null) {
+            return;
+        }
+
+        String pkgName = mContext != null ? mContext.getOpPackageName() : "<unknown>";
+        if (DBG) {
+            logd("register addOnOpportunisticSubscriptionsChangedListener pkgName=" + pkgName
+                    + " listener=" + listener);
+        }
+
+        listener.setExecutor(executor);
+
+        try {
+            // We use the TelephonyRegistry as it runs in the system and thus is always
+            // available. Where as SubscriptionController could crash and not be available
+            ITelephonyRegistry tr = ITelephonyRegistry.Stub.asInterface(ServiceManager.getService(
+                    "telephony.registry"));
+            if (tr != null) {
+                tr.addOnOpportunisticSubscriptionsChangedListener(pkgName, listener.callback);
+            }
+        } catch (RemoteException ex) {
+            Log.e(LOG_TAG, "Remote exception ITelephonyRegistry " + ex);
+        }
+    }
+
+    /**
+     * Unregister the {@link OnOpportunisticSubscriptionsChangedListener} that is currently
+     * listening opportunistic subscriptions change. This is not strictly necessary
+     * as the listener will automatically be unregistered if an attempt to invoke the listener
+     * fails.
+     *
+     * @param listener that is to be unregistered.
+     */
+    public void removeOnOpportunisticSubscriptionsChangedListener(
+            OnOpportunisticSubscriptionsChangedListener listener) {
+        String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
+        if (DBG) {
+            logd("unregister OnOpportunisticSubscriptionsChangedListener pkgForDebug="
+                    + pkgForDebug + " listener=" + listener);
+        }
+        try {
+            // We use the TelephonyRegistry as it runs in the system and thus is always
+            // available where as SubscriptionController could crash and not be available
+            ITelephonyRegistry tr = ITelephonyRegistry.Stub.asInterface(ServiceManager.getService(
+                    "telephony.registry"));
+            if (tr != null) {
+                tr.removeOnSubscriptionsChangedListener(pkgForDebug, listener.callback);
+            }
+        } catch (RemoteException ex) {
+            Log.e(LOG_TAG, "Remote exception ITelephonyRegistry " + ex);
         }
     }
 
@@ -1177,6 +1289,15 @@
 
     }
 
+    /**
+     * Get an array of Subscription Ids for specified slot Index.
+     * @param slotIndex the slot Index.
+     * @return subscription Ids or null if the given slot Index is not valid.
+     */
+    public static int[] getSubscriptionIds(int slotIndex) {
+        return getSubId(slotIndex);
+    }
+
     /** @hide */
     @UnsupportedAppUsage
     public static int[] getSubId(int slotIndex) {
diff --git a/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl b/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
index e0e1a7b..43d56b3 100644
--- a/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
@@ -32,6 +32,8 @@
 interface ITelephonyRegistry {
     void addOnSubscriptionsChangedListener(String pkg,
             IOnSubscriptionsChangedListener callback);
+    void addOnOpportunisticSubscriptionsChangedListener(String pkg,
+            IOnSubscriptionsChangedListener callback);
     void removeOnSubscriptionsChangedListener(String pkg,
             IOnSubscriptionsChangedListener callback);
     void listen(String pkg, IPhoneStateListener callback, int events, boolean notifyNow);
@@ -73,6 +75,7 @@
             int activationState, int activationType);
     void notifyOemHookRawEventForSubscriber(in int subId, in byte[] rawData);
     void notifySubscriptionInfoChanged();
+    void notifyOpportunisticSubscriptionInfoChanged();
     void notifyCarrierNetworkChange(in boolean active);
     void notifyUserMobileDataStateChangedForPhoneId(in int phoneId, in int subId, in boolean state);
     void notifyPhoneCapabilityChanged(in PhoneCapability capability);
diff --git a/test-base/Android.bp b/test-base/Android.bp
index d25b477..0b8a02a 100644
--- a/test-base/Android.bp
+++ b/test-base/Android.bp
@@ -19,9 +19,8 @@
 // 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 {
+java_sdk_library {
     name: "android.test.base",
-    installable: true,
 
     srcs: ["src/**/*.java"],
 
@@ -29,11 +28,38 @@
       javacflags: ["-Xep:DepAnn:ERROR"],
     },
 
+    hostdex: true,
+
+    api_packages: [
+        "android.test",
+        "android.test.suitebuilder.annotation",
+        "com.android.internal.util",
+        "junit.framework",
+    ],
+
+    droiddoc_options: ["stubsourceonly"],
+    compile_dex: true,
+}
+
+// Build the android.test.base_static library
+// ==========================================
+// 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.
+java_library_static {
+    name: "android.test.base_static",
+    installable: false,
+
+    srcs: ["src/**/*.java"],
+
+    errorprone: {
+        javacflags: ["-Xep:DepAnn:ERROR"],
+    },
+
     // Needs to be consistent with the repackaged version of this make target.
     java_version: "1.8",
 
     sdk_version: "current",
-    hostdex: true,
 }
 
 // Build the legacy-test library
@@ -46,7 +72,7 @@
     installable: true,
 
     sdk_version: "current",
-    static_libs: ["android.test.base"],
+    static_libs: ["android.test.base_static"],
 }
 
 // Build the repackaged.android.test.base library
@@ -57,7 +83,7 @@
     name: "repackaged.android.test.base",
 
     sdk_version: "current",
-    static_libs: ["android.test.base"],
+    static_libs: ["android.test.base_static"],
 
     jarjar_rules: "jarjar-rules.txt",
     // Pin java_version until jarjar is certified to support later versions. http://b/72703434
@@ -84,38 +110,3 @@
     ],
 }
 
-droiddoc {
-    name: "android-test-base-api-stubs-gen-docs",
-    srcs: [
-        "src/**/*.java",
-    ],
-    custom_template: "droiddoc-templates-sdk",
-    installable: false,
-    args: "-stubpackages android.test:" +
-          "android.test.suitebuilder.annotation:" +
-          "com.android.internal.util:" +
-          "junit.framework -stubsourceonly -nodocs",
-    sdk_version: "current",
-    api_tag_name: "ANDROID_TEST_BASE",
-    api_filename: "android-test-base-api.txt",
-    removed_api_filename: "android-test-base-removed.txt",
-}
-
-// Build the android.test.base.stubs library
-// =========================================
-java_library_static {
-    name: "android.test.base.stubs",
-    srcs: [
-        ":android-test-base-api-stubs-gen-docs",
-    ],
-    product_variables: {
-        pdk: {
-            enabled: false,
-        },
-        unbundled_build: {
-            enabled: false,
-        },
-    },
-    sdk_version: "current",
-    compile_dex: true,
-}
diff --git a/test-base/Android.mk b/test-base/Android.mk
index baf5726..a9d30cf 100644
--- a/test-base/Android.mk
+++ b/test-base/Android.mk
@@ -16,50 +16,6 @@
 
 LOCAL_PATH:= $(call my-dir)
 
-# For unbundled build we'll use the prebuilt jar from prebuilts/sdk.
-ifeq (,$(TARGET_BUILD_APPS)$(filter true,$(TARGET_BUILD_PDK)))
-
-ANDROID_TEST_BASE_API_FILE := $(LOCAL_PATH)/api/android-test-base-current.txt
-ANDROID_TEST_BASE_REMOVED_API_FILE := $(LOCAL_PATH)/api/android-test-base-removed.txt
-
-full_classes_jar := $(call intermediates-dir-for,JAVA_LIBRARIES,android.test.base.stubs,,COMMON)/classes.jar
-# Archive a copy of the classes.jar in SDK build.
-$(call dist-for-goals,sdk win_sdk,$(full_classes_jar):android.test.base.stubs.jar)
-
-# Check that the android.test.base.stubs library has not changed
-# ==============================================================
-
-# Check that the API we're building hasn't changed from the not-yet-released
-# SDK version.
-$(eval $(call check-api, \
-    check-android-test-base-api-current, \
-    $(ANDROID_TEST_BASE_API_FILE), \
-    $(INTERNAL_PLATFORM_ANDROID_TEST_BASE_API_FILE), \
-    $(ANDROID_TEST_BASE_REMOVED_API_FILE), \
-    $(INTERNAL_PLATFORM_ANDROID_TEST_BASE_REMOVED_API_FILE), \
-    -error 2 -error 3 -error 4 -error 5 -error 6 \
-    -error 7 -error 8 -error 9 -error 10 -error 11 -error 12 -error 13 -error 14 -error 15 \
-    -error 16 -error 17 -error 18 -error 19 -error 20 -error 21 -error 23 -error 24 \
-    -error 25 -error 26 -error 27, \
-    cat $(LOCAL_PATH)/api/apicheck_msg_android_test_base.txt, \
-    check-android-test-base-api, \
-    $(OUT_DOCS)/android-test-base-api-stubs-gen-docs-stubs.srcjar \
-    ))
-
-.PHONY: check-android-test-base-api
-checkapi: check-android-test-base-api
-
-.PHONY: update-android-test-base-api
-update-api: update-android-test-base-api
-
-update-android-test-base-api: $(INTERNAL_PLATFORM_ANDROID_TEST_BASE_API_FILE) | $(ACP)
-	@echo Copying current.txt
-	$(hide) $(ACP) $(INTERNAL_PLATFORM_ANDROID_TEST_BASE_API_FILE) $(ANDROID_TEST_BASE_API_FILE)
-	@echo Copying removed.txt
-	$(hide) $(ACP) $(INTERNAL_PLATFORM_ANDROID_TEST_BASE_REMOVED_API_FILE) $(ANDROID_TEST_BASE_REMOVED_API_FILE)
-
-endif  # not TARGET_BUILD_APPS not TARGET_BUILD_PDK=true
-
 ifeq ($(HOST_OS),linux)
 # Build the legacy-performance-test-hostdex library
 # =================================================
diff --git a/test-base/api/apicheck_msg_android_test_base.txt b/test-base/api/apicheck_msg_android_test_base.txt
deleted file mode 100644
index 144aecc..0000000
--- a/test-base/api/apicheck_msg_android_test_base.txt
+++ /dev/null
@@ -1,17 +0,0 @@
-
-******************************
-You have tried to change the API from what has been previously approved.
-
-To make these errors go away, you have two choices:
-   1) You can add "@hide" javadoc comments to the methods, etc. listed in the
-      errors above.
-
-   2) You can update android-test-base-current.txt by executing the following command:
-         make update-android-test-base-api
-
-      To submit the revised android-test-base-current.txt to the main Android repository,
-      you will need approval.
-******************************
-
-
-
diff --git a/test-base/api/android-test-base-current.txt b/test-base/api/current.txt
similarity index 100%
rename from test-base/api/android-test-base-current.txt
rename to test-base/api/current.txt
diff --git a/test-base/api/android-test-base-removed.txt b/test-base/api/removed.txt
similarity index 100%
copy from test-base/api/android-test-base-removed.txt
copy to test-base/api/removed.txt
diff --git a/test-base/api/android-test-base-removed.txt b/test-base/api/system-current.txt
similarity index 100%
copy from test-base/api/android-test-base-removed.txt
copy to test-base/api/system-current.txt
diff --git a/test-base/api/android-test-base-removed.txt b/test-base/api/system-removed.txt
similarity index 100%
rename from test-base/api/android-test-base-removed.txt
rename to test-base/api/system-removed.txt
diff --git a/test-base/api/android-test-base-removed.txt b/test-base/api/test-current.txt
similarity index 100%
copy from test-base/api/android-test-base-removed.txt
copy to test-base/api/test-current.txt
diff --git a/test-base/api/android-test-base-removed.txt b/test-base/api/test-removed.txt
similarity index 100%
copy from test-base/api/android-test-base-removed.txt
copy to test-base/api/test-removed.txt
diff --git a/test-legacy/Android.bp b/test-legacy/Android.bp
index d2af8a9..833c714 100644
--- a/test-legacy/Android.bp
+++ b/test-legacy/Android.bp
@@ -25,7 +25,7 @@
     static_libs: [
         "android.test.base-minus-junit",
         "android.test.runner-minus-junit",
-        "android.test.mock",
+        "android.test.mock.impl",
     ],
 
     no_framework_libs: true,
diff --git a/test-mock/Android.bp b/test-mock/Android.bp
index 8d3faae..5eba017 100644
--- a/test-mock/Android.bp
+++ b/test-mock/Android.bp
@@ -16,95 +16,15 @@
 
 // Build the android.test.mock library
 // ===================================
-java_library {
+java_sdk_library {
     name: "android.test.mock",
-    installable: true,
 
-    java_version: "1.8",
     srcs: ["src/**/*.java"],
 
-    no_framework_libs: true,
-    libs: [
-        "framework",
+    api_packages: [
+        "android.test.mock",
     ],
-}
 
-doc_defaults {
-    name:"android.test.mock.docs-defaults",
-    srcs: ["src/android/test/mock/**/*.java"],
-
-    // Includes the main framework source to ensure that doclava has access to the
-    // visibility information for the base classes of the mock classes. Without it
-    // otherwise hidden methods could be visible.
-    srcs_lib: "framework",
-    srcs_lib_whitelist_dirs: ["core/java"],
     srcs_lib_whitelist_pkgs: ["android"],
-    libs: [
-        "core-oj",
-        "core-libart",
-        "framework",
-        "conscrypt",
-        "okhttp",
-        "bouncycastle",
-        "ext",
-    ],
-    local_sourcepaths: ["src/android/test/mock"],
-    custom_template: "droiddoc-templates-sdk",
-    installable: false,
-}
-
-android_test_mock_docs_args =
-    "-hide 110 -hide 111 -hide 113 -hide 121 -hide 125 -hide 126 -hide 127 -hide 128 " +
-    "-stubpackages android.test.mock " +
-    "-nodocs "
-
-droiddoc {
-    name: "android.test.mock.docs",
-    defaults: ["android.test.mock.docs-defaults"],
-
-    api_tag_name: "ANDROID_TEST_MOCK",
-    api_filename: "api/android-test-mock-current.txt",
-    removed_api_filename: "api/android-test-mock-removed.txt",
-
-    args: android_test_mock_docs_args,
-}
-
-droiddoc {
-    name: "android.test.mock.docs-system",
-    defaults: ["android.test.mock.docs-defaults"],
-
-    api_tag_name: "ANDROID_TEST_MOCK_SYSTEM",
-    api_filename: "api/android-test-mock-system-current.txt",
-    removed_api_filename: "api/android-test-mock-system-removed.txt",
-
-    args: android_test_mock_docs_args +
-        "-showAnnotation android.annotation.SystemApi ",
-}
-
-java_library_static {
-    name: "android.test.mock.stubs",
-    srcs: [":android.test.mock.docs"],
-    sdk_version: "current",
-    product_variables: {
-        unbundled_build: {
-            // Unbundled apps will use the prebuilt one
-            // prebuilts/sdk/current
-            enabled: false,
-        },
-    },
-    compile_dex: true,
-}
-
-java_library_static {
-    name: "android.test.mock.stubs-system",
-    srcs: [":android.test.mock.docs-system"],
-    sdk_version: "system_current",
-    product_variables: {
-        unbundled_build: {
-            // Unbundled apps will use the prebuilt one
-            // prebuilts/sdk/system_current
-            enabled: false,
-        },
-    },
     compile_dex: true,
 }
diff --git a/test-mock/Android.mk b/test-mock/Android.mk
deleted file mode 100644
index 73a7340..0000000
--- a/test-mock/Android.mk
+++ /dev/null
@@ -1,93 +0,0 @@
-#
-# Copyright (C) 2008 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)
-
-# Archive a copy of the classes.jar in SDK build.
-full_classes_jar := $(call intermediates-dir-for,JAVA_LIBRARIES,android.test.mock.stubs,,COMMON)/classes.jar
-$(call dist-for-goals,sdk win_sdk,$(full_classes_jar):android.test.mock.stubs.jar)
-
-# Check that the android.test.mock.stubs library has not changed
-# ==============================================================
-ANDROID_TEST_MOCK_API_FILE := $(LOCAL_PATH)/api/android-test-mock-current.txt
-ANDROID_TEST_MOCK_REMOVED_API_FILE := $(LOCAL_PATH)/api/android-test-mock-removed.txt
-
-# Check that the API we're building hasn't changed from the not-yet-released
-# SDK version.
-$(eval $(call check-api, \
-    check-android-test-mock-api-current, \
-    $(ANDROID_TEST_MOCK_API_FILE), \
-    $(INTERNAL_PLATFORM_ANDROID_TEST_MOCK_API_FILE), \
-    $(ANDROID_TEST_MOCK_REMOVED_API_FILE), \
-    $(INTERNAL_PLATFORM_ANDROID_TEST_MOCK_REMOVED_API_FILE), \
-    -error 2 -error 3 -error 4 -error 5 -error 6 \
-    -error 7 -error 8 -error 9 -error 10 -error 11 -error 12 -error 13 -error 14 -error 15 \
-    -error 16 -error 17 -error 18 -error 19 -error 20 -error 21 -error 23 -error 24 \
-    -error 25 -error 26 -error 27, \
-    cat $(LOCAL_PATH)/api/apicheck_msg_android_test_mock.txt, \
-    check-android-test-mock-api, \
-    $(OUT_DOCS)/android.test.mock.docs-stubs.srcjar \
-    ))
-
-.PHONY: check-android-test-mock-api
-checkapi: check-android-test-mock-api
-
-.PHONY: update-android-test-mock-api
-update-api: update-android-test-mock-api
-
-update-android-test-mock-api: $(INTERNAL_PLATFORM_ANDROID_TEST_MOCK_API_FILE) | $(ACP)
-	@echo Copying current.txt
-	$(hide) $(ACP) $(INTERNAL_PLATFORM_ANDROID_TEST_MOCK_API_FILE) $(ANDROID_TEST_MOCK_API_FILE)
-	@echo Copying removed.txt
-	$(hide) $(ACP) $(INTERNAL_PLATFORM_ANDROID_TEST_MOCK_REMOVED_API_FILE) $(ANDROID_TEST_MOCK_REMOVED_API_FILE)
-
-# Archive a copy of the classes.jar in SDK build.
-full_classes_jar := $(call intermediates-dir-for,JAVA_LIBRARIES,android.test.mock.stubs-system,,COMMON)/classes.jar
-$(call dist-for-goals,sdk win_sdk,$(full_classes_jar):android.test.mock.stubs_system.jar)
-
-# Check that the android.test.mock.stubs-system library has not changed
-# =====================================================================
-ANDROID_TEST_MOCK_SYSTEM_API_FILE := $(LOCAL_PATH)/api/android-test-mock-system-current.txt
-ANDROID_TEST_MOCK_SYSTEM_REMOVED_API_FILE := $(LOCAL_PATH)/api/android-test-mock-system-removed.txt
-
-# Check that the API we're building hasn't changed from the not-yet-released
-# SDK version.
-$(eval $(call check-api, \
-    check-android-test-mock-system-api-current, \
-    $(ANDROID_TEST_MOCK_SYSTEM_API_FILE), \
-    $(INTERNAL_PLATFORM_ANDROID_TEST_MOCK_SYSTEM_API_FILE), \
-    $(ANDROID_TEST_MOCK_SYSTEM_REMOVED_API_FILE), \
-    $(INTERNAL_PLATFORM_ANDROID_TEST_MOCK_SYSTEM_REMOVED_API_FILE), \
-    -error 2 -error 3 -error 4 -error 5 -error 6 \
-    -error 7 -error 8 -error 9 -error 10 -error 11 -error 12 -error 13 -error 14 -error 15 \
-    -error 16 -error 17 -error 18 -error 19 -error 20 -error 21 -error 23 -error 24 \
-    -error 25 -error 26 -error 27, \
-    cat $(LOCAL_PATH)/api/apicheck_msg_android_test_mock-system.txt, \
-    check-android-test-mock-system-api, \
-    $(OUT_DOCS)/android.test.mock.docs-system-stubs.srcjar \
-    ))
-
-.PHONY: check-android-test-mock-system-api
-checkapi: check-android-test-mock-system-api
-
-.PHONY: update-android-test-mock-system-api
-update-api: update-android-test-mock-system-api
-
-update-android-test-mock-system-api: $(INTERNAL_PLATFORM_ANDROID_TEST_MOCK_SYSTEM_API_FILE) | $(ACP)
-	@echo Copying current.txt
-	$(hide) $(ACP) $(INTERNAL_PLATFORM_ANDROID_TEST_MOCK_SYSTEM_API_FILE) $(ANDROID_TEST_MOCK_SYSTEM_API_FILE)
-	@echo Copying removed.txt
-	$(hide) $(ACP) $(INTERNAL_PLATFORM_ANDROID_TEST_MOCK_SYSTEM_REMOVED_API_FILE) $(ANDROID_TEST_MOCK_SYSTEM_REMOVED_API_FILE)
diff --git a/test-mock/api/apicheck_msg_android_test_mock-system.txt b/test-mock/api/apicheck_msg_android_test_mock-system.txt
deleted file mode 100644
index 3a97117..0000000
--- a/test-mock/api/apicheck_msg_android_test_mock-system.txt
+++ /dev/null
@@ -1,17 +0,0 @@
-
-******************************
-You have tried to change the API from what has been previously approved.
-
-To make these errors go away, you have two choices:
-   1) You can add "@hide" javadoc comments to the methods, etc. listed in the
-      errors above.
-
-   2) You can update android-test-mock-current.txt by executing the following command:
-         make update-android-test-mock-system-api
-
-      To submit the revised android-test-mock-system-current.txt to the main Android repository,
-      you will need approval.
-******************************
-
-
-
diff --git a/test-mock/api/apicheck_msg_android_test_mock.txt b/test-mock/api/apicheck_msg_android_test_mock.txt
deleted file mode 100644
index e388935..0000000
--- a/test-mock/api/apicheck_msg_android_test_mock.txt
+++ /dev/null
@@ -1,17 +0,0 @@
-
-******************************
-You have tried to change the API from what has been previously approved.
-
-To make these errors go away, you have two choices:
-   1) You can add "@hide" javadoc comments to the methods, etc. listed in the
-      errors above.
-
-   2) You can update android-test-mock-current.txt by executing the following command:
-         make update-android-test-mock-api
-
-      To submit the revised android-test-mock-current.txt to the main Android repository,
-      you will need approval.
-******************************
-
-
-
diff --git a/test-mock/api/android-test-mock-current.txt b/test-mock/api/current.txt
similarity index 100%
rename from test-mock/api/android-test-mock-current.txt
rename to test-mock/api/current.txt
diff --git a/test-mock/api/android-test-mock-removed.txt b/test-mock/api/removed.txt
similarity index 100%
rename from test-mock/api/android-test-mock-removed.txt
rename to test-mock/api/removed.txt
diff --git a/test-mock/api/android-test-mock-system-current.txt b/test-mock/api/system-current.txt
similarity index 100%
rename from test-mock/api/android-test-mock-system-current.txt
rename to test-mock/api/system-current.txt
diff --git a/test-mock/api/android-test-mock-system-removed.txt b/test-mock/api/system-removed.txt
similarity index 100%
rename from test-mock/api/android-test-mock-system-removed.txt
rename to test-mock/api/system-removed.txt
diff --git a/test-mock/api/test-current.txt b/test-mock/api/test-current.txt
new file mode 100644
index 0000000..725ea93
--- /dev/null
+++ b/test-mock/api/test-current.txt
@@ -0,0 +1,16 @@
+package android.test.mock {
+
+  public deprecated class MockPackageManager extends android.content.pm.PackageManager {
+    method public java.lang.String getDefaultBrowserPackageNameAsUser(int);
+    method public int getInstallReason(java.lang.String, android.os.UserHandle);
+    method public java.util.List<android.content.pm.ApplicationInfo> getInstalledApplicationsAsUser(int, int);
+    method public java.util.List<android.content.pm.PackageInfo> getInstalledPackagesAsUser(int, int);
+    method public java.lang.String[] getNamesForUids(int[]);
+    method public java.lang.String getPermissionControllerPackageName();
+    method public java.lang.String getServicesSystemSharedLibraryPackageName();
+    method public java.lang.String getSharedSystemSharedLibraryPackageName();
+    method public boolean isPermissionReviewModeEnabled();
+  }
+
+}
+
diff --git a/test-mock/api/android-test-mock-system-removed.txt b/test-mock/api/test-removed.txt
similarity index 100%
copy from test-mock/api/android-test-mock-system-removed.txt
copy to test-mock/api/test-removed.txt
diff --git a/test-runner/Android.bp b/test-runner/Android.bp
index 2caa6c4..ea615b9 100644
--- a/test-runner/Android.bp
+++ b/test-runner/Android.bp
@@ -16,23 +16,32 @@
 
 // Build the android.test.runner library
 // =====================================
-java_library {
+java_sdk_library {
     name: "android.test.runner",
-    installable: true,
 
-    // Needs to be consistent with the repackaged version of this make target.
-    java_version: "1.8",
     srcs: ["src/**/*.java"],
 
     errorprone: {
         javacflags: ["-Xep:DepAnn:ERROR"],
     },
 
-    sdk_version: "current",
     libs: [
         "android.test.base",
-        "android.test.mock.stubs",
+        "android.test.mock",
     ],
+    stub_only_libs: [
+        "android.test.base",
+        "android.test.mock",
+    ],
+    api_packages: [
+        "android.test",
+        "android.test.suitebuilder",
+        "junit.runner",
+        "junit.textui",
+    ],
+
+    droiddoc_options: ["stubsourceonly"],
+    compile_dex: true
 }
 
 // Build the android.test.runner-minus-junit library
@@ -46,8 +55,8 @@
 
     sdk_version: "current",
     libs: [
-        "android.test.base",
-        "android.test.mock.stubs",
+        "android.test.base_static",
+        "android.test.mock",
         "junit",
     ],
 }
@@ -70,7 +79,7 @@
 
     sdk_version: "current",
     libs: [
-        "android.test.base",
+        "android.test.base_static",
     ],
 
     jarjar_rules: "jarjar-rules.txt",
@@ -78,48 +87,3 @@
     java_version: "1.8",
 }
 
-droiddoc {
-    name: "android-test-runner-api-stubs-gen-docs",
-    srcs: [
-        "src/**/*.java",
-    ],
-    libs: [
-        "core-oj",
-        "core-libart",
-        "framework",
-        "android.test.base",
-        "android.test.mock",
-    ],
-    custom_template: "droiddoc-templates-sdk",
-    installable: false,
-    args: "-stubpackages android.test:" +
-          "android.test.suitebuilder:" +
-          "junit.runner:" +
-          "junit.textui -stubsourceonly -nodocs",
-    api_tag_name: "ANDROID_TEST_RUNNER",
-    api_filename: "android-test-runner-current.txt",
-    removed_api_filename: "android-test-runner-removed.txt",
-}
-
-// Build the android.test.runner.stubs library
-// =========================================
-java_library_static {
-    name: "android.test.runner.stubs",
-    srcs: [
-        ":android-test-runner-api-stubs-gen-docs",
-    ],
-    libs: [
-        "android.test.base.stubs",
-        "android.test.mock.stubs",
-    ],
-    product_variables: {
-        pdk: {
-            enabled: false,
-        },
-        unbundled_build: {
-            enabled: false,
-        },
-    },
-    sdk_version: "current",
-    compile_dex: true,
-}
diff --git a/test-runner/Android.mk b/test-runner/Android.mk
index b70d249..18bde85 100644
--- a/test-runner/Android.mk
+++ b/test-runner/Android.mk
@@ -16,49 +16,5 @@
 
 LOCAL_PATH:= $(call my-dir)
 
-# For unbundled build we'll use the prebuilt jar from prebuilts/sdk.
-ifeq (,$(TARGET_BUILD_APPS)$(filter true,$(TARGET_BUILD_PDK)))
-
-ANDROID_TEST_RUNNER_API_FILE := $(LOCAL_PATH)/api/android-test-runner-current.txt
-ANDROID_TEST_RUNNER_REMOVED_API_FILE := $(LOCAL_PATH)/api/android-test-runner-removed.txt
-
-full_classes_jar := $(call intermediates-dir-for,JAVA_LIBRARIES,android.test.runner.stubs,,COMMON)/classes.jar
-# Archive a copy of the classes.jar in SDK build.
-$(call dist-for-goals,sdk win_sdk,$(full_classes_jar):android.test.runner.stubs.jar)
-
-# Check that the android.test.runner.stubs library has not changed
-# ================================================================
-
-# Check that the API we're building hasn't changed from the not-yet-released
-# SDK version.
-$(eval $(call check-api, \
-    check-android-test-runner-api-current, \
-    $(ANDROID_TEST_RUNNER_API_FILE), \
-    $(INTERNAL_PLATFORM_ANDROID_TEST_RUNNER_API_FILE), \
-    $(ANDROID_TEST_RUNNER_REMOVED_API_FILE), \
-    $(INTERNAL_PLATFORM_ANDROID_TEST_RUNNER_REMOVED_API_FILE), \
-    -error 2 -error 3 -error 4 -error 5 -error 6 \
-    -error 7 -error 8 -error 9 -error 10 -error 11 -error 12 -error 13 -error 14 -error 15 \
-    -error 16 -error 17 -error 18 -error 19 -error 20 -error 21 -error 23 -error 24 \
-    -error 25 -error 26 -error 27, \
-    cat $(LOCAL_PATH)/api/apicheck_msg_android_test_runner.txt, \
-    check-android-test-runner-api, \
-    $(OUT_DOCS)/android-test-runner-api-stubs-gen-docs-stubs.srcjar  \
-    ))
-
-.PHONY: check-android-test-runner-api
-checkapi: check-android-test-runner-api
-
-.PHONY: update-android-test-runner-api
-update-api: update-android-test-runner-api
-
-update-android-test-runner-api: $(INTERNAL_PLATFORM_ANDROID_TEST_RUNNER_API_FILE) | $(ACP)
-	@echo Copying current.txt
-	$(hide) $(ACP) $(INTERNAL_PLATFORM_ANDROID_TEST_RUNNER_API_FILE) $(ANDROID_TEST_RUNNER_API_FILE)
-	@echo Copying removed.txt
-	$(hide) $(ACP) $(INTERNAL_PLATFORM_ANDROID_TEST_RUNNER_REMOVED_API_FILE) $(ANDROID_TEST_RUNNER_REMOVED_API_FILE)
-
-endif  # not TARGET_BUILD_APPS not TARGET_BUILD_PDK=true
-
 # additionally, build unit tests in a separate .apk
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/test-runner/api/apicheck_msg_android_test_runner.txt b/test-runner/api/apicheck_msg_android_test_runner.txt
deleted file mode 100644
index cf2d15e..0000000
--- a/test-runner/api/apicheck_msg_android_test_runner.txt
+++ /dev/null
@@ -1,17 +0,0 @@
-
-******************************
-You have tried to change the API from what has been previously approved.
-
-To make these errors go away, you have two choices:
-   1) You can add "@hide" javadoc comments to the methods, etc. listed in the
-      errors above.
-
-   2) You can update android-test-runner-current.txt by executing the following command:
-         make update-android-test-runner-api
-
-      To submit the revised android-test-runner-current.txt to the main Android repository,
-      you will need approval.
-******************************
-
-
-
diff --git a/test-runner/api/android-test-runner-current.txt b/test-runner/api/current.txt
similarity index 100%
rename from test-runner/api/android-test-runner-current.txt
rename to test-runner/api/current.txt
diff --git a/test-runner/api/android-test-runner-removed.txt b/test-runner/api/removed.txt
similarity index 100%
copy from test-runner/api/android-test-runner-removed.txt
copy to test-runner/api/removed.txt
diff --git a/test-runner/api/android-test-runner-removed.txt b/test-runner/api/system-current.txt
similarity index 100%
copy from test-runner/api/android-test-runner-removed.txt
copy to test-runner/api/system-current.txt
diff --git a/test-runner/api/android-test-runner-removed.txt b/test-runner/api/system-removed.txt
similarity index 100%
rename from test-runner/api/android-test-runner-removed.txt
rename to test-runner/api/system-removed.txt
diff --git a/test-runner/api/android-test-runner-removed.txt b/test-runner/api/test-current.txt
similarity index 100%
copy from test-runner/api/android-test-runner-removed.txt
copy to test-runner/api/test-current.txt
diff --git a/test-runner/api/android-test-runner-removed.txt b/test-runner/api/test-removed.txt
similarity index 100%
copy from test-runner/api/android-test-runner-removed.txt
copy to test-runner/api/test-removed.txt
diff --git a/tests/TtsTests/src/com/android/speech/tts/TextToSpeechTests.java b/tests/TtsTests/src/com/android/speech/tts/TextToSpeechTests.java
index 918873b..d9bb7db 100644
--- a/tests/TtsTests/src/com/android/speech/tts/TextToSpeechTests.java
+++ b/tests/TtsTests/src/com/android/speech/tts/TextToSpeechTests.java
@@ -28,6 +28,7 @@
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
 import org.mockito.stubbing.Stubber;
+import org.mockito.quality.Strictness;
 import junit.framework.Assert;
 
 import java.util.Locale;
@@ -210,12 +211,16 @@
     }
 
     public static abstract class CountDownBehaviour extends StubberImpl {
+        public CountDownBehaviour(Strictness strictness) {
+            super(strictness);
+        }
+
         /** Used to mock methods that return a result. */
         public abstract Stubber andReturn(Object result);
     }
 
     public static CountDownBehaviour doCountDown(final CountDownLatch latch) {
-        return new CountDownBehaviour() {
+        return new CountDownBehaviour(Strictness.WARN) {
             @Override
             public <T> T when(T mock) {
                 return Mockito.doAnswer(new Answer<Void>() {
@@ -229,7 +234,7 @@
 
             @Override
             public Stubber andReturn(final Object result) {
-                return new StubberImpl() {
+                return new StubberImpl(Strictness.WARN) {
                     @Override
                     public <T> T when(T mock) {
                         return Mockito.doAnswer(new Answer<Object>() {
diff --git a/tests/testables/Android.bp b/tests/testables/Android.bp
new file mode 100644
index 0000000..f07f09d
--- /dev/null
+++ b/tests/testables/Android.bp
@@ -0,0 +1,32 @@
+//
+// Copyright (C) 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+java_library {
+
+    name: "testables",
+    // ANDROIDMK TRANSLATION ERROR: unsupported assignment to LOCAL_MODULE_TAG
+    // LOCAL_MODULE_TAG := tests
+
+    srcs: ["src/**/*.java"],
+
+    libs: [
+        "android.test.runner",
+        "android.test.mock",
+        "android-support-test",
+        "mockito-target-inline-minus-junit4",
+    ],
+
+}
diff --git a/tests/testables/Android.mk b/tests/testables/Android.mk
deleted file mode 100644
index f3cbac0..0000000
--- a/tests/testables/Android.mk
+++ /dev/null
@@ -1,32 +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 := testables
-LOCAL_MODULE_TAG := tests
-
-LOCAL_SRC_FILES := $(call all-java-files-under,src)
-
-LOCAL_JAVA_LIBRARIES := android.test.runner android.test.mock \
-    android-support-test \
-    mockito-target-inline-minus-junit4
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tools/aosp/aosp_sha.sh b/tools/aosp/aosp_sha.sh
new file mode 100755
index 0000000..e50c70d
--- /dev/null
+++ b/tools/aosp/aosp_sha.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+LOCAL_DIR="$( dirname "${BASH_SOURCE}" )"
+
+if git branch -vv | grep -q -P "^\*[^\[]+\[aosp/"; then
+    # Change appears to be in AOSP
+    exit 0
+else
+    # Change appears to be non-AOSP; search for files
+    count=0
+    while read -r file ; do
+        if (( count == 0 )); then
+            echo
+        fi
+        echo -e "\033[0;31mThe source of truth for '$file' is in AOSP.\033[0m"
+        (( count++ ))
+    done < <(git show --name-only --pretty=format: $1 | grep -- "$2")
+    if (( count != 0 )); then
+        echo
+        echo "If your change contains no confidential details (such as security fixes), please"
+        echo "upload and merge this change at https://android-review.googlesource.com/."
+        echo
+        exit 77
+    fi
+fi
diff --git a/tools/hiddenapi/generate_hiddenapi_lists.py b/tools/hiddenapi/generate_hiddenapi_lists.py
index 4a0931a..6c46e67 100755
--- a/tools/hiddenapi/generate_hiddenapi_lists.py
+++ b/tools/hiddenapi/generate_hiddenapi_lists.py
@@ -59,6 +59,8 @@
 def read_lines(filename):
     """Reads entire file and return it as a list of lines.
 
+    Lines which begin with a hash are ignored.
+
     Args:
         filename (string): Path to the file to read from.
 
@@ -66,7 +68,7 @@
         list: Lines of the loaded file as a list of strings.
     """
     with open(filename, 'r') as f:
-        return f.readlines()
+        return filter(lambda line: not line.startswith('#'), f.readlines())
 
 def write_lines(filename, lines):
     """Writes list of lines into a file, overwriting the file it it exists.
diff --git a/tools/hiddenapi/sort_api.sh b/tools/hiddenapi/sort_api.sh
index 1c6eb1b..bdcc807 100755
--- a/tools/hiddenapi/sort_api.sh
+++ b/tools/hiddenapi/sort_api.sh
@@ -11,8 +11,14 @@
 readarray A < "$source_list"
 # Sort
 IFS=$'\n'
+# Stash away comments
+C=( $(grep -E '^#' <<< "${A[*]}") )
+A=( $(grep -v -E '^#' <<< "${A[*]}") )
+# Sort entries
 A=( $(LC_COLLATE=C sort -f <<< "${A[*]}") )
 A=( $(uniq <<< "${A[*]}") )
+# Concatenate comments and entries
+A=( ${C[*]} ${A[*]} )
 unset IFS
 # Dump array back into the file
 printf '%s\n' "${A[@]}" > "$dest_list"
diff --git a/tools/processors/unsupportedappusage/Android.bp b/tools/processors/unsupportedappusage/Android.bp
new file mode 100644
index 0000000..1aca3ed
--- /dev/null
+++ b/tools/processors/unsupportedappusage/Android.bp
@@ -0,0 +1,25 @@
+
+java_library_host {
+    name: "unsupportedappusage-annotation-processor",
+    java_resources: [
+        "META-INF/**/*",
+    ],
+    srcs: [
+        "src/**/*.java",
+    ],
+    static_libs: [
+        "guava",
+        "unsupportedappusage-annotation"
+    ],
+    openjdk9: {
+        javacflags: [
+            "--add-modules=jdk.compiler",
+            "--add-exports jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED",
+            "--add-exports jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED",
+            "--add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED",
+            "--add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED",
+        ],
+    },
+
+    use_tools_jar: true,
+}
diff --git a/tools/processors/unsupportedappusage/META-INF/services/javax.annotation.processing.Processor b/tools/processors/unsupportedappusage/META-INF/services/javax.annotation.processing.Processor
new file mode 100644
index 0000000..4a969d3
--- /dev/null
+++ b/tools/processors/unsupportedappusage/META-INF/services/javax.annotation.processing.Processor
@@ -0,0 +1 @@
+android.processor.unsupportedappusage.UnsupportedAppUsageProcessor
diff --git a/tools/processors/unsupportedappusage/src/android/processor/unsupportedappusage/SignatureBuilder.java b/tools/processors/unsupportedappusage/src/android/processor/unsupportedappusage/SignatureBuilder.java
new file mode 100644
index 0000000..ef29146
--- /dev/null
+++ b/tools/processors/unsupportedappusage/src/android/processor/unsupportedappusage/SignatureBuilder.java
@@ -0,0 +1,228 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.processor.unsupportedappusage;
+
+import static javax.lang.model.element.ElementKind.PACKAGE;
+import static javax.tools.Diagnostic.Kind.ERROR;
+import static javax.tools.Diagnostic.Kind.WARNING;
+
+import android.annotation.UnsupportedAppUsage;
+
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableMap;
+import com.sun.tools.javac.code.Type;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.processing.Messager;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.PackageElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.ArrayType;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+
+/**
+ * Builds a dex signature for a given method or field.
+ */
+public class SignatureBuilder {
+
+    private static final Map<TypeKind, String> TYPE_MAP = ImmutableMap.<TypeKind, String>builder()
+            .put(TypeKind.BOOLEAN, "Z")
+            .put(TypeKind.BYTE, "B")
+            .put(TypeKind.CHAR, "C")
+            .put(TypeKind.DOUBLE, "D")
+            .put(TypeKind.FLOAT, "F")
+            .put(TypeKind.INT, "I")
+            .put(TypeKind.LONG, "J")
+            .put(TypeKind.SHORT, "S")
+            .put(TypeKind.VOID, "V")
+            .build();
+
+    private final Messager mMessager;
+
+    /**
+     * Exception used internally when we can't build a signature. Whenever this is thrown, an error
+     * will also be written to the Messager.
+     */
+    private class SignatureBuilderException extends Exception {
+        public SignatureBuilderException(String message) {
+            super(message);
+        }
+        public void report(Element offendingElement) {
+            mMessager.printMessage(ERROR, getMessage(), offendingElement);
+        }
+    }
+
+    public SignatureBuilder(Messager messager) {
+        mMessager = messager;
+    }
+
+    /**
+     * Returns a list of enclosing elements for the given element, with the package first, and
+     * excluding the element itself.
+     */
+    private List<Element> getEnclosingElements(Element e) {
+        List<Element> enclosing = new ArrayList<>();
+        e = e.getEnclosingElement(); // don't include the element itself.
+        while (e != null) {
+            enclosing.add(e);
+            e = e.getEnclosingElement();
+        }
+        Collections.reverse(enclosing);
+        return enclosing;
+    }
+
+    /**
+     * Get the dex signature for a clazz, in format "Lpackage/name/Outer$Inner;"
+     */
+    private String getClassSignature(TypeElement clazz) {
+        StringBuilder sb = new StringBuilder("L");
+        for (Element enclosing : getEnclosingElements(clazz)) {
+            if (enclosing.getKind() == PACKAGE) {
+                sb.append(((PackageElement) enclosing)
+                        .getQualifiedName()
+                        .toString()
+                        .replace('.', '/'));
+                sb.append('/');
+            } else {
+                sb.append(enclosing.getSimpleName()).append('$');
+            }
+
+        }
+        return sb
+                .append(clazz.getSimpleName())
+                .append(";")
+                .toString();
+    }
+
+    /**
+     * Returns the type signature for a given type. For primitive types, a single character.
+     * For classes, the class signature. For arrays, a "[" preceeding the component type.
+     */
+    private String getTypeSignature(TypeMirror type) throws SignatureBuilderException {
+        String sig = TYPE_MAP.get(type.getKind());
+        if (sig != null) {
+            return sig;
+        }
+        switch (type.getKind()) {
+            case ARRAY:
+                return "[" + getTypeSignature(((ArrayType) type).getComponentType());
+            case DECLARED:
+                Element declaring = ((DeclaredType) type).asElement();
+                if (!(declaring instanceof TypeElement)) {
+                    throw new SignatureBuilderException(
+                            "Can't handle declared type of kind " + declaring.getKind());
+                }
+                return getClassSignature((TypeElement) declaring);
+            case TYPEVAR:
+                Type.TypeVar typeVar = (Type.TypeVar) type;
+                if (typeVar.getLowerBound().getKind() != TypeKind.NULL) {
+                    return getTypeSignature(typeVar.getLowerBound());
+                } else if (typeVar.getUpperBound().getKind() != TypeKind.NULL) {
+                    return getTypeSignature(typeVar.getUpperBound());
+                } else {
+                    throw new SignatureBuilderException("Can't handle typevar with no bound");
+                }
+
+            default:
+                throw new SignatureBuilderException("Can't handle type of kind " + type.getKind());
+        }
+    }
+
+    /**
+     * Get the signature for an executable, either a method or a constructor.
+     *
+     * @param name "<init>" for  constructor, else the method name
+     * @param method The executable element in question.
+     */
+    private String getExecutableSignature(CharSequence name, ExecutableElement method)
+            throws SignatureBuilderException {
+        StringBuilder sig = new StringBuilder();
+        sig.append(getClassSignature((TypeElement) method.getEnclosingElement()))
+                .append("->")
+                .append(name)
+                .append("(");
+        for (VariableElement param : method.getParameters()) {
+            sig.append(getTypeSignature(param.asType()));
+        }
+        sig.append(")")
+                .append(getTypeSignature(method.getReturnType()));
+        return sig.toString();
+    }
+
+    private String buildMethodSignature(ExecutableElement method) throws SignatureBuilderException {
+        return getExecutableSignature(method.getSimpleName(), method);
+    }
+
+    private String buildConstructorSignature(ExecutableElement cons)
+            throws SignatureBuilderException {
+        return getExecutableSignature("<init>", cons);
+    }
+
+    private String buildFieldSignature(VariableElement field) throws SignatureBuilderException {
+        StringBuilder sig = new StringBuilder();
+        sig.append(getClassSignature((TypeElement) field.getEnclosingElement()))
+                .append("->")
+                .append(field.getSimpleName())
+                .append(":")
+                .append(getTypeSignature(field.asType()))
+        ;
+        return sig.toString();
+    }
+
+    public String buildSignature(Element element) {
+        UnsupportedAppUsage uba = element.getAnnotation(UnsupportedAppUsage.class);
+        try {
+            String signature;
+            switch (element.getKind()) {
+                case METHOD:
+                    signature = buildMethodSignature((ExecutableElement) element);
+                    break;
+                case CONSTRUCTOR:
+                    signature = buildConstructorSignature((ExecutableElement) element);
+                    break;
+                case FIELD:
+                    signature = buildFieldSignature((VariableElement) element);
+                    break;
+                default:
+                    return null;
+            }
+            // if we have an expected signature on the annotation, warn if it doesn't match.
+            if (!Strings.isNullOrEmpty(uba.expectedSignature())) {
+                if (!signature.equals(uba.expectedSignature())) {
+                    mMessager.printMessage(
+                            WARNING,
+                            String.format("Expected signature doesn't match generated signature.\n"
+                                            + " Expected:  %s\n Generated: %s",
+                                    uba.expectedSignature(), signature),
+                            element);
+                }
+            }
+            return signature;
+        } catch (SignatureBuilderException problem) {
+            problem.report(element);
+            return null;
+        }
+    }
+}
diff --git a/tools/processors/unsupportedappusage/src/android/processor/unsupportedappusage/UnsupportedAppUsageProcessor.java b/tools/processors/unsupportedappusage/src/android/processor/unsupportedappusage/UnsupportedAppUsageProcessor.java
new file mode 100644
index 0000000..1d4c435
--- /dev/null
+++ b/tools/processors/unsupportedappusage/src/android/processor/unsupportedappusage/UnsupportedAppUsageProcessor.java
@@ -0,0 +1,173 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.processor.unsupportedappusage;
+
+import static javax.tools.StandardLocation.CLASS_OUTPUT;
+
+import android.annotation.UnsupportedAppUsage;
+
+import com.google.common.base.Joiner;
+import com.sun.tools.javac.model.JavacElements;
+import com.sun.tools.javac.tree.JCTree;
+import com.sun.tools.javac.util.Pair;
+import com.sun.tools.javac.util.Position;
+
+import java.io.IOException;
+import java.io.PrintStream;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.stream.Stream;
+
+import javax.annotation.processing.AbstractProcessor;
+import javax.annotation.processing.RoundEnvironment;
+import javax.annotation.processing.SupportedAnnotationTypes;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.TypeElement;
+
+/**
+ * Annotation processor for {@link UnsupportedAppUsage} annotations.
+ *
+ * This processor currently outputs two things:
+ * 1. A greylist.txt containing dex signatures of all annotated elements.
+ * 2. A CSV file with a mapping of dex signatures to corresponding source positions.
+ *
+ * The first will be used at a later stage of the build to add access flags to the dex file. The
+ * second is used for automating updates to the annotations themselves.
+ */
+@SupportedAnnotationTypes({"android.annotation.UnsupportedAppUsage"})
+public class UnsupportedAppUsageProcessor extends AbstractProcessor {
+
+    // Package name for writing output. Output will be written to the "class output" location within
+    // this package.
+    private static final String PACKAGE = "unsupportedappusage";
+    private static final String INDEX_CSV = "unsupportedappusage_index.csv";
+
+    @Override
+    public SourceVersion getSupportedSourceVersion() {
+        return SourceVersion.latest();
+    }
+
+    /**
+     * Write the contents of a stream to a text file, with one line per item.
+     */
+    private void writeToFile(String name,
+            String headerLine,
+            Stream<?> contents) throws IOException {
+        PrintStream out = new PrintStream(processingEnv.getFiler().createResource(
+                CLASS_OUTPUT,
+                PACKAGE,
+                name)
+                .openOutputStream());
+        out.println(headerLine);
+        contents.forEach(o -> out.println(o));
+        if (out.checkError()) {
+            throw new IOException("Error when writing to " + name);
+        }
+        out.close();
+    }
+
+    /**
+     * Find the annotation mirror for the @UnsupportedAppUsage annotation on the given element.
+     */
+    private AnnotationMirror getUnsupportedAppUsageAnnotationMirror(Element e) {
+        for (AnnotationMirror m : e.getAnnotationMirrors()) {
+            TypeElement type = (TypeElement) m.getAnnotationType().asElement();
+            if (type.getQualifiedName().toString().equals(
+                    UnsupportedAppUsage.class.getCanonicalName())) {
+                return m;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Returns a CSV header line for the columns returned by
+     * {@link #getAnnotationIndex(String, Element)}.
+     */
+    private String getCsvHeaders() {
+        return Joiner.on(',').join(
+                "signature",
+                "file",
+                "startline",
+                "startcol",
+                "endline",
+                "endcol"
+        );
+    }
+
+    /**
+     * Maps an annotated element to the source position of the @UnsupportedAppUsage annotation
+     * attached to it. It returns CSV in the format:
+     *   dex-signature,filename,start-line,start-col,end-line,end-col
+     *
+     * The positions refer to the annotation itself, *not* the annotated member. This can therefore
+     * be used to read just the annotation from the file, and to perform in-place edits on it.
+     *
+     * @param signature the dex signature for the element.
+     * @param annotatedElement The annotated element
+     * @return A single line of CSV text
+     */
+    private String getAnnotationIndex(String signature, Element annotatedElement) {
+        JavacElements javacElem = (JavacElements) processingEnv.getElementUtils();
+        AnnotationMirror unsupportedAppUsage =
+                getUnsupportedAppUsageAnnotationMirror(annotatedElement);
+        Pair<JCTree, JCTree.JCCompilationUnit> pair =
+                javacElem.getTreeAndTopLevel(annotatedElement, unsupportedAppUsage, null);
+        Position.LineMap lines = pair.snd.lineMap;
+        return Joiner.on(",").join(
+                signature,
+                pair.snd.getSourceFile().getName(),
+                lines.getLineNumber(pair.fst.pos().getStartPosition()),
+                lines.getColumnNumber(pair.fst.pos().getStartPosition()),
+                lines.getLineNumber(pair.fst.pos().getEndPosition(pair.snd.endPositions)),
+                lines.getColumnNumber(pair.fst.pos().getEndPosition(pair.snd.endPositions)));
+    }
+
+    /**
+     * This is the main entry point in the processor, called by the compiler.
+     */
+    @Override
+    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
+        Set<? extends Element> annotated = roundEnv.getElementsAnnotatedWith(
+                UnsupportedAppUsage.class);
+        if (annotated.size() == 0) {
+            return true;
+        }
+        // build signatures for each annotated member, and put them in a map of signature to member
+        Map<String, Element> signatureMap = new TreeMap<>();
+        SignatureBuilder sb = new SignatureBuilder(processingEnv.getMessager());
+        for (Element e : annotated) {
+            String sig = sb.buildSignature(e);
+            if (sig != null) {
+                signatureMap.put(sig, e);
+            }
+        }
+        try {
+            writeToFile(INDEX_CSV,
+                    getCsvHeaders(),
+                    signatureMap.entrySet()
+                            .stream()
+                            .map(e -> getAnnotationIndex(e.getKey() ,e.getValue())));
+        } catch (IOException e) {
+            throw new RuntimeException("Failed to write output", e);
+        }
+        return true;
+    }
+}