Merge "Correct PendingIntent#getActivity() flags"
diff --git a/Android.bp b/Android.bp
index aeaaca3d..a93a155 100644
--- a/Android.bp
+++ b/Android.bp
@@ -371,7 +371,7 @@
 java_library {
     name: "framework-updatable-stubs-module_libs_api",
     static_libs: [
-        "framework-sdkextensions-stubs-module_libs_api",
+        "framework-sdkextensions.stubs.module_lib",
         "framework-tethering.stubs.module_lib",
         "updatable_media_stubs",
     ],
diff --git a/cmds/telecom/src/com/android/commands/telecom/Telecom.java b/cmds/telecom/src/com/android/commands/telecom/Telecom.java
index 9707405..35f4add 100644
--- a/cmds/telecom/src/com/android/commands/telecom/Telecom.java
+++ b/cmds/telecom/src/com/android/commands/telecom/Telecom.java
@@ -64,6 +64,8 @@
     private static final String COMMAND_UNREGISTER_PHONE_ACCOUNT = "unregister-phone-account";
     private static final String COMMAND_SET_DEFAULT_DIALER = "set-default-dialer";
     private static final String COMMAND_GET_DEFAULT_DIALER = "get-default-dialer";
+    private static final String COMMAND_STOP_BLOCK_SUPPRESSION = "stop-block-suppression";
+
     /**
      * Change the system dialer package name if a package name was specified,
      * Example: adb shell telecom set-system-dialer <PACKAGE>
@@ -111,6 +113,8 @@
                 + "usage: telecom set-sim-count <COUNT>\n"
                 + "usage: telecom get-sim-config\n"
                 + "usage: telecom get-max-phones\n"
+                + "usage: telecom stop-block-suppression: Stop suppressing the blocked number"
+                        + " provider after a call to emergency services.\n"
                 + "usage: telecom set-emer-phone-account-filter <PACKAGE>\n"
                 + "\n"
                 + "telecom set-phone-account-enabled: Enables the given phone account, if it has"
@@ -203,6 +207,9 @@
             case COMMAND_UNREGISTER_PHONE_ACCOUNT:
                 runUnregisterPhoneAccount();
                 break;
+            case COMMAND_STOP_BLOCK_SUPPRESSION:
+                runStopBlockSuppression();
+                break;
             case COMMAND_SET_DEFAULT_DIALER:
                 runSetDefaultDialer();
                 break;
@@ -320,8 +327,13 @@
         System.out.println("Success - " + handle + " unregistered.");
     }
 
+    private void runStopBlockSuppression() throws RemoteException {
+        mTelecomService.stopBlockSuppression();
+    }
+
     private void runSetDefaultDialer() throws RemoteException {
-        final String packageName = nextArgRequired();
+        String packageName = nextArg();
+        if ("default".equals(packageName)) packageName = null;
         mTelecomService.setTestDefaultDialer(packageName);
         System.out.println("Success - " + packageName + " set as override default dialer.");
     }
diff --git a/core/java/android/bluetooth/BluetoothHeadsetClient.java b/core/java/android/bluetooth/BluetoothHeadsetClient.java
index 85e0e08..2836325 100644
--- a/core/java/android/bluetooth/BluetoothHeadsetClient.java
+++ b/core/java/android/bluetooth/BluetoothHeadsetClient.java
@@ -19,7 +19,6 @@
 import android.Manifest;
 import android.annotation.NonNull;
 import android.annotation.RequiresPermission;
-import android.annotation.SystemApi;
 import android.compat.annotation.UnsupportedAppUsage;
 import android.content.Context;
 import android.os.Binder;
@@ -587,7 +586,6 @@
      * @return true if connectionPolicy is set, false on error
      * @hide
      */
-    @SystemApi
     @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)
     public boolean setConnectionPolicy(@NonNull BluetoothDevice device,
             @ConnectionPolicy int connectionPolicy) {
@@ -637,7 +635,6 @@
      * @return connection policy of the device
      * @hide
      */
-    @SystemApi
     @RequiresPermission(Manifest.permission.BLUETOOTH)
     public @ConnectionPolicy int getConnectionPolicy(@NonNull BluetoothDevice device) {
         if (VDBG) log("getConnectionPolicy(" + device + ")");
diff --git a/core/java/android/bluetooth/BluetoothMapClient.java b/core/java/android/bluetooth/BluetoothMapClient.java
index 19240dc..4f5c4fe 100644
--- a/core/java/android/bluetooth/BluetoothMapClient.java
+++ b/core/java/android/bluetooth/BluetoothMapClient.java
@@ -19,7 +19,6 @@
 import android.Manifest;
 import android.annotation.NonNull;
 import android.annotation.RequiresPermission;
-import android.annotation.SystemApi;
 import android.app.PendingIntent;
 import android.compat.annotation.UnsupportedAppUsage;
 import android.content.Context;
@@ -276,7 +275,6 @@
      * @return true if connectionPolicy is set, false on error
      * @hide
      */
-    @SystemApi
     @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)
     public boolean setConnectionPolicy(@NonNull BluetoothDevice device,
             @ConnectionPolicy int connectionPolicy) {
@@ -325,7 +323,6 @@
      * @return connection policy of the device
      * @hide
      */
-    @SystemApi
     @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)
     public @ConnectionPolicy int getConnectionPolicy(@NonNull BluetoothDevice device) {
         if (VDBG) Log.d(TAG, "getConnectionPolicy(" + device + ")");
diff --git a/core/java/android/bluetooth/BluetoothPbapClient.java b/core/java/android/bluetooth/BluetoothPbapClient.java
index d3452ff..f356da1 100644
--- a/core/java/android/bluetooth/BluetoothPbapClient.java
+++ b/core/java/android/bluetooth/BluetoothPbapClient.java
@@ -19,7 +19,6 @@
 import android.Manifest;
 import android.annotation.NonNull;
 import android.annotation.RequiresPermission;
-import android.annotation.SystemApi;
 import android.content.Context;
 import android.os.Binder;
 import android.os.IBinder;
@@ -276,7 +275,6 @@
      * @return true if connectionPolicy is set, false on error
      * @hide
      */
-    @SystemApi
     @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)
     public boolean setConnectionPolicy(@NonNull BluetoothDevice device,
             @ConnectionPolicy int connectionPolicy) {
@@ -329,7 +327,6 @@
      * @return connection policy of the device
      * @hide
      */
-    @SystemApi
     @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)
     public @ConnectionPolicy int getConnectionPolicy(@NonNull BluetoothDevice device) {
         if (VDBG) {
diff --git a/core/java/android/bluetooth/BluetoothSap.java b/core/java/android/bluetooth/BluetoothSap.java
index 6e03481..48e8c1a 100644
--- a/core/java/android/bluetooth/BluetoothSap.java
+++ b/core/java/android/bluetooth/BluetoothSap.java
@@ -18,7 +18,6 @@
 
 import android.Manifest;
 import android.annotation.RequiresPermission;
-import android.annotation.SystemApi;
 import android.compat.annotation.UnsupportedAppUsage;
 import android.content.Context;
 import android.os.Binder;
@@ -328,7 +327,6 @@
      * @return true if connectionPolicy is set, false on error
      * @hide
      */
-    @SystemApi
     @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)
     public boolean setConnectionPolicy(BluetoothDevice device,
             @ConnectionPolicy int connectionPolicy) {
@@ -377,7 +375,6 @@
      * @return connection policy of the device
      * @hide
      */
-    @SystemApi
     @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)
     public @ConnectionPolicy int getConnectionPolicy(BluetoothDevice device) {
         if (VDBG) log("getConnectionPolicy(" + device + ")");
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index 0e61016..62669e0 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -46,7 +46,6 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.StringRes;
-import android.annotation.TestApi;
 import android.apex.ApexInfo;
 import android.app.ActivityTaskManager;
 import android.app.ActivityThread;
@@ -2682,7 +2681,6 @@
      *         not compatible with this platform
      * @hide Exposed for unit testing only.
      */
-    @TestApi
     public static int computeTargetSdkVersion(@IntRange(from = 0) int targetVers,
             @Nullable String targetCode, @NonNull String[] platformSdkCodenames,
             @NonNull String[] outError) {
@@ -2747,7 +2745,6 @@
      *         compatible with this platform
      * @hide Exposed for unit testing only.
      */
-    @TestApi
     public static int computeMinSdkVersion(@IntRange(from = 1) int minVers,
             @Nullable String minCode, @IntRange(from = 1) int platformSdkVersion,
             @NonNull String[] platformSdkCodenames, @NonNull String[] outError) {
@@ -4845,7 +4842,6 @@
      *                                AndroidManifest.xml.
      * @hide Exposed for unit testing only.
      */
-    @TestApi
     public static int getActivityConfigChanges(int configChanges, int recreateOnConfigChanges) {
         return configChanges | ((~recreateOnConfigChanges) & RECREATE_ON_CONFIG_CHANGES_MASK);
     }
diff --git a/core/java/android/hardware/GeomagneticField.java b/core/java/android/hardware/GeomagneticField.java
index 0d7b695..cbfe4fa 100644
--- a/core/java/android/hardware/GeomagneticField.java
+++ b/core/java/android/hardware/GeomagneticField.java
@@ -16,7 +16,8 @@
 
 package android.hardware;
 
-import java.util.GregorianCalendar;
+import java.util.Calendar;
+import java.util.TimeZone;
 
 /**
  * Estimates magnetic field at a given point on
@@ -26,7 +27,7 @@
  * <p>This uses the World Magnetic Model produced by the United States National
  * Geospatial-Intelligence Agency.  More details about the model can be found at
  * <a href="http://www.ngdc.noaa.gov/geomag/WMM/DoDWMM.shtml">http://www.ngdc.noaa.gov/geomag/WMM/DoDWMM.shtml</a>.
- * This class currently uses WMM-2015 which is valid until 2020, but should
+ * This class currently uses WMM-2020 which is valid until 2025, but should
  * produce acceptable results for several years after that. Future versions of
  * Android may use a newer version of the model.
  */
@@ -48,69 +49,72 @@
     static private final float EARTH_REFERENCE_RADIUS_KM = 6371.2f;
 
     // These coefficients and the formulae used below are from:
-    // NOAA Technical Report: The US/UK World Magnetic Model for 2015-2020
-    static private final float[][] G_COEFF = new float[][] {
-        { 0.0f },
-        { -29438.5f, -1501.1f },
-        { -2445.3f, 3012.5f, 1676.6f },
-        { 1351.1f, -2352.3f, 1225.6f, 581.9f },
-        { 907.2f, 813.7f, 120.3f, -335.0f, 70.3f },
-        { -232.6f, 360.1f, 192.4f, -141.0f, -157.4f, 4.3f },
-        { 69.5f, 67.4f, 72.8f, -129.8f, -29.0f, 13.2f, -70.9f },
-        { 81.6f, -76.1f, -6.8f, 51.9f, 15.0f, 9.3f, -2.8f, 6.7f },
-        { 24.0f, 8.6f, -16.9f, -3.2f, -20.6f, 13.3f, 11.7f, -16.0f, -2.0f },
-        { 5.4f, 8.8f, 3.1f, -3.1f, 0.6f, -13.3f, -0.1f, 8.7f, -9.1f, -10.5f },
-        { -1.9f, -6.5f, 0.2f, 0.6f, -0.6f, 1.7f, -0.7f, 2.1f, 2.3f, -1.8f, -3.6f },
-        { 3.1f, -1.5f, -2.3f, 2.1f, -0.9f, 0.6f, -0.7f, 0.2f, 1.7f, -0.2f, 0.4f, 3.5f },
-        { -2.0f, -0.3f, 0.4f, 1.3f, -0.9f, 0.9f, 0.1f, 0.5f, -0.4f, -0.4f, 0.2f, -0.9f, 0.0f } };
+    // NOAA Technical Report: The US/UK World Magnetic Model for 2020-2025
+    static private final float[][] G_COEFF = new float[][]{
+            {0.0f},
+            {-29404.5f, -1450.7f},
+            {-2500.0f, 2982.0f, 1676.8f},
+            {1363.9f, -2381.0f, 1236.2f, 525.7f},
+            {903.1f, 809.4f, 86.2f, -309.4f, 47.9f},
+            {-234.4f, 363.1f, 187.8f, -140.7f, -151.2f, 13.7f},
+            {65.9f, 65.6f, 73.0f, -121.5f, -36.2f, 13.5f, -64.7f},
+            {80.6f, -76.8f, -8.3f, 56.5f, 15.8f, 6.4f, -7.2f, 9.8f},
+            {23.6f, 9.8f, -17.5f, -0.4f, -21.1f, 15.3f, 13.7f, -16.5f, -0.3f},
+            {5.0f, 8.2f, 2.9f, -1.4f, -1.1f, -13.3f, 1.1f, 8.9f, -9.3f, -11.9f},
+            {-1.9f, -6.2f, -0.1f, 1.7f, -0.9f, 0.6f, -0.9f, 1.9f, 1.4f, -2.4f, -3.9f},
+            {3.0f, -1.4f, -2.5f, 2.4f, -0.9f, 0.3f, -0.7f, -0.1f, 1.4f, -0.6f, 0.2f, 3.1f},
+            {-2.0f, -0.1f, 0.5f, 1.3f, -1.2f, 0.7f, 0.3f, 0.5f, -0.2f, -0.5f, 0.1f, -1.1f, -0.3f}};
 
-    static private final float[][] H_COEFF = new float[][] {
-        { 0.0f },
-        { 0.0f, 4796.2f },
-        { 0.0f, -2845.6f, -642.0f },
-        { 0.0f, -115.3f, 245.0f, -538.3f },
-        { 0.0f, 283.4f, -188.6f, 180.9f, -329.5f },
-        { 0.0f, 47.4f, 196.9f, -119.4f, 16.1f, 100.1f },
-        { 0.0f, -20.7f, 33.2f, 58.8f, -66.5f, 7.3f, 62.5f },
-        { 0.0f, -54.1f, -19.4f, 5.6f, 24.4f, 3.3f, -27.5f, -2.3f },
-        { 0.0f, 10.2f, -18.1f, 13.2f, -14.6f, 16.2f, 5.7f, -9.1f, 2.2f },
-        { 0.0f, -21.6f, 10.8f, 11.7f, -6.8f, -6.9f, 7.8f, 1.0f, -3.9f, 8.5f },
-        { 0.0f, 3.3f, -0.3f, 4.6f, 4.4f, -7.9f, -0.6f, -4.1f, -2.8f, -1.1f, -8.7f },
-        { 0.0f, -0.1f, 2.1f, -0.7f, -1.1f, 0.7f, -0.2f, -2.1f, -1.5f, -2.5f, -2.0f, -2.3f },
-        { 0.0f, -1.0f, 0.5f, 1.8f, -2.2f, 0.3f, 0.7f, -0.1f, 0.3f, 0.2f, -0.9f, -0.2f, 0.7f } };
+    static private final float[][] H_COEFF = new float[][]{
+            {0.0f},
+            {0.0f, 4652.9f},
+            {0.0f, -2991.6f, -734.8f},
+            {0.0f, -82.2f, 241.8f, -542.9f},
+            {0.0f, 282.0f, -158.4f, 199.8f, -350.1f},
+            {0.0f, 47.7f, 208.4f, -121.3f, 32.2f, 99.1f},
+            {0.0f, -19.1f, 25.0f, 52.7f, -64.4f, 9.0f, 68.1f},
+            {0.0f, -51.4f, -16.8f, 2.3f, 23.5f, -2.2f, -27.2f, -1.9f},
+            {0.0f, 8.4f, -15.3f, 12.8f, -11.8f, 14.9f, 3.6f, -6.9f, 2.8f},
+            {0.0f, -23.3f, 11.1f, 9.8f, -5.1f, -6.2f, 7.8f, 0.4f, -1.5f, 9.7f},
+            {0.0f, 3.4f, -0.2f, 3.5f, 4.8f, -8.6f, -0.1f, -4.2f, -3.4f, -0.1f, -8.8f},
+            {0.0f, 0.0f, 2.6f, -0.5f, -0.4f, 0.6f, -0.2f, -1.7f, -1.6f, -3.0f, -2.0f, -2.6f},
+            {0.0f, -1.2f, 0.5f, 1.3f, -1.8f, 0.1f, 0.7f, -0.1f, 0.6f, 0.2f, -0.9f, 0.0f, 0.5f}};
 
-    static private final float[][] DELTA_G = new float[][] {
-        { 0.0f },
-        { 10.7f, 17.9f },
-        { -8.6f, -3.3f, 2.4f },
-        { 3.1f, -6.2f, -0.4f, -10.4f },
-        { -0.4f, 0.8f, -9.2f, 4.0f, -4.2f },
-        { -0.2f, 0.1f, -1.4f, 0.0f, 1.3f, 3.8f },
-        { -0.5f, -0.2f, -0.6f, 2.4f, -1.1f, 0.3f, 1.5f },
-        { 0.2f, -0.2f, -0.4f, 1.3f, 0.2f, -0.4f, -0.9f, 0.3f },
-        { 0.0f, 0.1f, -0.5f, 0.5f, -0.2f, 0.4f, 0.2f, -0.4f, 0.3f },
-        { 0.0f, -0.1f, -0.1f, 0.4f, -0.5f, -0.2f, 0.1f, 0.0f, -0.2f, -0.1f },
-        { 0.0f, 0.0f, -0.1f, 0.3f, -0.1f, -0.1f, -0.1f, 0.0f, -0.2f, -0.1f, -0.2f },
-        { 0.0f, 0.0f, -0.1f, 0.1f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.1f, -0.1f },
-        { 0.1f, 0.0f, 0.0f, 0.1f, -0.1f, 0.0f, 0.1f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f } };
+    static private final float[][] DELTA_G = new float[][]{
+            {0.0f},
+            {6.7f, 7.7f},
+            {-11.5f, -7.1f, -2.2f},
+            {2.8f, -6.2f, 3.4f, -12.2f},
+            {-1.1f, -1.6f, -6.0f, 5.4f, -5.5f},
+            {-0.3f, 0.6f, -0.7f, 0.1f, 1.2f, 1.0f},
+            {-0.6f, -0.4f, 0.5f, 1.4f, -1.4f, 0.0f, 0.8f},
+            {-0.1f, -0.3f, -0.1f, 0.7f, 0.2f, -0.5f, -0.8f, 1.0f},
+            {-0.1f, 0.1f, -0.1f, 0.5f, -0.1f, 0.4f, 0.5f, 0.0f, 0.4f},
+            {-0.1f, -0.2f, 0.0f, 0.4f, -0.3f, 0.0f, 0.3f, 0.0f, 0.0f, -0.4f},
+            {0.0f, 0.0f, 0.0f, 0.2f, -0.1f, -0.2f, 0.0f, -0.1f, -0.2f, -0.1f, 0.0f},
+            {0.0f, -0.1f, 0.0f, 0.0f, 0.0f, -0.1f, 0.0f, 0.0f, -0.1f, -0.1f, -0.1f, -0.1f},
+            {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.1f}};
 
-    static private final float[][] DELTA_H = new float[][] {
-        { 0.0f },
-        { 0.0f, -26.8f },
-        { 0.0f, -27.1f, -13.3f },
-        { 0.0f, 8.4f, -0.4f, 2.3f },
-        { 0.0f, -0.6f, 5.3f, 3.0f, -5.3f },
-        { 0.0f, 0.4f, 1.6f, -1.1f, 3.3f, 0.1f },
-        { 0.0f, 0.0f, -2.2f, -0.7f, 0.1f, 1.0f, 1.3f },
-        { 0.0f, 0.7f, 0.5f, -0.2f, -0.1f, -0.7f, 0.1f, 0.1f },
-        { 0.0f, -0.3f, 0.3f, 0.3f, 0.6f, -0.1f, -0.2f, 0.3f, 0.0f },
-        { 0.0f, -0.2f, -0.1f, -0.2f, 0.1f, 0.1f, 0.0f, -0.2f, 0.4f, 0.3f },
-        { 0.0f, 0.1f, -0.1f, 0.0f, 0.0f, -0.2f, 0.1f, -0.1f, -0.2f, 0.1f, -0.1f },
-        { 0.0f, 0.0f, 0.1f, 0.0f, 0.1f, 0.0f, 0.0f, 0.1f, 0.0f, -0.1f, 0.0f, -0.1f },
-        { 0.0f, 0.0f, 0.0f, -0.1f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f } };
+    static private final float[][] DELTA_H = new float[][]{
+            {0.0f},
+            {0.0f, -25.1f},
+            {0.0f, -30.2f, -23.9f},
+            {0.0f, 5.7f, -1.0f, 1.1f},
+            {0.0f, 0.2f, 6.9f, 3.7f, -5.6f},
+            {0.0f, 0.1f, 2.5f, -0.9f, 3.0f, 0.5f},
+            {0.0f, 0.1f, -1.8f, -1.4f, 0.9f, 0.1f, 1.0f},
+            {0.0f, 0.5f, 0.6f, -0.7f, -0.2f, -1.2f, 0.2f, 0.3f},
+            {0.0f, -0.3f, 0.7f, -0.2f, 0.5f, -0.3f, -0.5f, 0.4f, 0.1f},
+            {0.0f, -0.3f, 0.2f, -0.4f, 0.4f, 0.1f, 0.0f, -0.2f, 0.5f, 0.2f},
+            {0.0f, 0.0f, 0.1f, -0.3f, 0.1f, -0.2f, 0.1f, 0.0f, -0.1f, 0.2f, 0.0f},
+            {0.0f, 0.0f, 0.1f, 0.0f, 0.2f, 0.0f, 0.0f, 0.1f, 0.0f, -0.1f, 0.0f, 0.0f},
+            {0.0f, 0.0f, 0.0f, -0.1f, 0.1f, 0.0f, 0.0f, 0.0f, 0.1f, 0.0f, 0.0f, 0.0f, -0.1f}};
 
-    static private final long BASE_TIME =
-            new GregorianCalendar(2015, 1, 1).getTimeInMillis();
+    static private final long BASE_TIME = new Calendar.Builder()
+            .setTimeZone(TimeZone.getTimeZone("UTC"))
+            .setDate(2020, Calendar.JANUARY, 1)
+            .build()
+            .getTimeInMillis();
 
     // The ratio between the Gauss-normalized associated Legendre functions and
     // the Schmid quasi-normalized ones. Compute these once staticly since they
@@ -190,7 +194,7 @@
         // We now compute the magnetic field strength given the geocentric
         // location. The magnetic field is the derivative of the potential
         // function defined by the model. See NOAA Technical Report: The US/UK
-        // World Magnetic Model for 2015-2020 for the derivation.
+        // World Magnetic Model for 2020-2025 for the derivation.
         float gcX = 0.0f;  // Geocentric northwards component.
         float gcY = 0.0f;  // Geocentric eastwards component.
         float gcZ = 0.0f;  // Geocentric downwards component.
@@ -203,7 +207,7 @@
 
                 // Negative derivative with respect to latitude, divided by
                 // radius.  This looks like the negation of the version in the
-                // NOAA Techincal report because that report used
+                // NOAA Technical report because that report used
                 // P_n^m(sin(theta)) and we use P_n^m(cos(90 - theta)), so the
                 // derivative with respect to theta is negated.
                 gcX += relativeRadiusPower[n+2]
diff --git a/core/java/android/net/DnsPacket.java b/core/java/android/net/DnsPacket.java
deleted file mode 100644
index 83e57e0..0000000
--- a/core/java/android/net/DnsPacket.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.net;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.text.TextUtils;
-
-import com.android.internal.util.BitUtils;
-
-import java.nio.BufferUnderflowException;
-import java.nio.ByteBuffer;
-import java.text.DecimalFormat;
-import java.text.FieldPosition;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Defines basic data for DNS protocol based on RFC 1035.
- * Subclasses create the specific format used in DNS packet.
- *
- * @hide
- */
-public abstract class DnsPacket {
-    public class DnsHeader {
-        private static final String TAG = "DnsHeader";
-        public final int id;
-        public final int flags;
-        public final int rcode;
-        private final int[] mRecordCount;
-
-        /**
-         * Create a new DnsHeader from a positioned ByteBuffer.
-         *
-         * The ByteBuffer must be in network byte order (which is the default).
-         * Reads the passed ByteBuffer from its current position and decodes a DNS header.
-         * When this constructor returns, the reading position of the ByteBuffer has been
-         * advanced to the end of the DNS header record.
-         * This is meant to chain with other methods reading a DNS response in sequence.
-         */
-        DnsHeader(@NonNull ByteBuffer buf) throws BufferUnderflowException {
-            id = BitUtils.uint16(buf.getShort());
-            flags = BitUtils.uint16(buf.getShort());
-            rcode = flags & 0xF;
-            mRecordCount = new int[NUM_SECTIONS];
-            for (int i = 0; i < NUM_SECTIONS; ++i) {
-                mRecordCount[i] = BitUtils.uint16(buf.getShort());
-            }
-        }
-
-        /**
-         * Get record count by type.
-         */
-        public int getRecordCount(int type) {
-            return mRecordCount[type];
-        }
-    }
-
-    /**
-     * Superclass for DNS questions and DNS resource records.
-     *
-     * DNS questions (No TTL/RDATA)
-     * DNS resource records (With TTL/RDATA)
-     */
-    public class DnsRecord {
-        private static final int MAXNAMESIZE = 255;
-        private static final int MAXLABELSIZE = 63;
-        private static final int MAXLABELCOUNT = 128;
-        private static final int NAME_NORMAL = 0;
-        private static final int NAME_COMPRESSION = 0xC0;
-        private final DecimalFormat byteFormat = new DecimalFormat();
-        private final FieldPosition pos = new FieldPosition(0);
-
-        private static final String TAG = "DnsRecord";
-
-        public final String dName;
-        public final int nsType;
-        public final int nsClass;
-        public final long ttl;
-        private final byte[] mRdata;
-
-        /**
-         * Create a new DnsRecord from a positioned ByteBuffer.
-         *
-         * Reads the passed ByteBuffer from its current position and decodes a DNS record.
-         * When this constructor returns, the reading position of the ByteBuffer has been
-         * advanced to the end of the DNS header record.
-         * This is meant to chain with other methods reading a DNS response in sequence.
-         *
-         * @param ByteBuffer input of record, must be in network byte order
-         *         (which is the default).
-         */
-        DnsRecord(int recordType, @NonNull ByteBuffer buf)
-                throws BufferUnderflowException, ParseException {
-            dName = parseName(buf, 0 /* Parse depth */);
-            if (dName.length() > MAXNAMESIZE) {
-                throw new ParseException(
-                        "Parse name fail, name size is too long: " + dName.length());
-            }
-            nsType = BitUtils.uint16(buf.getShort());
-            nsClass = BitUtils.uint16(buf.getShort());
-
-            if (recordType != QDSECTION) {
-                ttl = BitUtils.uint32(buf.getInt());
-                final int length = BitUtils.uint16(buf.getShort());
-                mRdata = new byte[length];
-                buf.get(mRdata);
-            } else {
-                ttl = 0;
-                mRdata = null;
-            }
-        }
-
-        /**
-         * Get a copy of rdata.
-         */
-        @Nullable
-        public byte[] getRR() {
-            return (mRdata == null) ? null : mRdata.clone();
-        }
-
-        /**
-         * Convert label from {@code byte[]} to {@code String}
-         *
-         * Follows the same conversion rules of the native code (ns_name.c in libc)
-         */
-        private String labelToString(@NonNull byte[] label) {
-            final StringBuffer sb = new StringBuffer();
-            for (int i = 0; i < label.length; ++i) {
-                int b = BitUtils.uint8(label[i]);
-                // Control characters and non-ASCII characters.
-                if (b <= 0x20 || b >= 0x7f) {
-                    // Append the byte as an escaped decimal number, e.g., "\19" for 0x13.
-                    sb.append('\\');
-                    byteFormat.format(b, sb, pos);
-                } else if (b == '"' || b == '.' || b == ';' || b == '\\'
-                        || b == '(' || b == ')' || b == '@' || b == '$') {
-                    // Append the byte as an escaped character, e.g., "\:" for 0x3a.
-                    sb.append('\\');
-                    sb.append((char) b);
-                } else {
-                    // Append the byte as a character, e.g., "a" for 0x61.
-                    sb.append((char) b);
-                }
-            }
-            return sb.toString();
-        }
-
-        private String parseName(@NonNull ByteBuffer buf, int depth) throws
-                BufferUnderflowException, ParseException {
-            if (depth > MAXLABELCOUNT) {
-                throw new ParseException("Failed to parse name, too many labels");
-            }
-            final int len = BitUtils.uint8(buf.get());
-            final int mask = len & NAME_COMPRESSION;
-            if (0 == len) {
-                return "";
-            } else if (mask != NAME_NORMAL && mask != NAME_COMPRESSION) {
-                throw new ParseException("Parse name fail, bad label type");
-            } else if (mask == NAME_COMPRESSION) {
-                // Name compression based on RFC 1035 - 4.1.4 Message compression
-                final int offset = ((len & ~NAME_COMPRESSION) << 8) + BitUtils.uint8(buf.get());
-                final int oldPos = buf.position();
-                if (offset >= oldPos - 2) {
-                    throw new ParseException("Parse compression name fail, invalid compression");
-                }
-                buf.position(offset);
-                final String pointed = parseName(buf, depth + 1);
-                buf.position(oldPos);
-                return pointed;
-            } else {
-                final byte[] label = new byte[len];
-                buf.get(label);
-                final String head = labelToString(label);
-                if (head.length() > MAXLABELSIZE) {
-                    throw new ParseException("Parse name fail, invalid label length");
-                }
-                final String tail = parseName(buf, depth + 1);
-                return TextUtils.isEmpty(tail) ? head : head + "." + tail;
-            }
-        }
-    }
-
-    public static final int QDSECTION = 0;
-    public static final int ANSECTION = 1;
-    public static final int NSSECTION = 2;
-    public static final int ARSECTION = 3;
-    private static final int NUM_SECTIONS = ARSECTION + 1;
-
-    private static final String TAG = DnsPacket.class.getSimpleName();
-
-    protected final DnsHeader mHeader;
-    protected final List<DnsRecord>[] mRecords;
-
-    protected DnsPacket(@NonNull byte[] data) throws ParseException {
-        if (null == data) throw new ParseException("Parse header failed, null input data");
-        final ByteBuffer buffer;
-        try {
-            buffer = ByteBuffer.wrap(data);
-            mHeader = new DnsHeader(buffer);
-        } catch (BufferUnderflowException e) {
-            throw new ParseException("Parse Header fail, bad input data", e);
-        }
-
-        mRecords = new ArrayList[NUM_SECTIONS];
-
-        for (int i = 0; i < NUM_SECTIONS; ++i) {
-            final int count = mHeader.getRecordCount(i);
-            if (count > 0) {
-                mRecords[i] = new ArrayList(count);
-            }
-            for (int j = 0; j < count; ++j) {
-                try {
-                    mRecords[i].add(new DnsRecord(i, buffer));
-                } catch (BufferUnderflowException e) {
-                    throw new ParseException("Parse record fail", e);
-                }
-            }
-        }
-    }
-}
diff --git a/core/java/android/net/DnsResolver.java b/core/java/android/net/DnsResolver.java
index 0b1a845..3f7660f 100644
--- a/core/java/android/net/DnsResolver.java
+++ b/core/java/android/net/DnsResolver.java
@@ -38,6 +38,8 @@
 import android.system.ErrnoException;
 import android.util.Log;
 
+import com.android.net.module.util.DnsPacket;
+
 import java.io.FileDescriptor;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -97,7 +99,7 @@
     @interface DnsError {}
     /**
      * Indicates that there was an error parsing the response the query.
-     * The cause of this error is available via getCause() and is a ParseException.
+     * The cause of this error is available via getCause() and is a {@link ParseException}.
      */
     public static final int ERROR_PARSE = 0;
     /**
@@ -290,8 +292,15 @@
             }
             try {
                 mAllAnswers.addAll(new DnsAddressAnswer(answer).getAddresses());
-            } catch (ParseException e) {
-                mDnsException = new DnsException(ERROR_PARSE, e);
+            } catch (DnsPacket.ParseException e) {
+                // Convert the com.android.net.module.util.DnsPacket.ParseException to an
+                // android.net.ParseException. This is the type that was used in Q and is implied
+                // by the public documentation of ERROR_PARSE.
+                //
+                // DnsPacket cannot throw android.net.ParseException directly because it's @hide.
+                ParseException pe = new ParseException(e.reason, e.getCause());
+                pe.setStackTrace(e.getStackTrace());
+                mDnsException = new DnsException(ERROR_PARSE, pe);
             }
             maybeReportAnswer();
         }
diff --git a/core/java/android/net/NetworkUtils.java b/core/java/android/net/NetworkUtils.java
index 779f7bc..0b92b95 100644
--- a/core/java/android/net/NetworkUtils.java
+++ b/core/java/android/net/NetworkUtils.java
@@ -155,6 +155,14 @@
     public static native Network getDnsNetwork() throws ErrnoException;
 
     /**
+     * Allow/Disallow creating AF_INET/AF_INET6 sockets and DNS lookups for current process.
+     *
+     * @param allowNetworking whether to allow or disallow creating AF_INET/AF_INET6 sockets
+     *                        and DNS lookups.
+     */
+    public static native void setAllowNetworkingForProcess(boolean allowNetworking);
+
+    /**
      * Get the tcp repair window associated with the {@code fd}.
      *
      * @param fd the tcp socket's {@link FileDescriptor}.
diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java
index 994ed21..3377867 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -194,6 +194,13 @@
      */
     public static final int FSVERITY_CERT_UID = 1075;
 
+    /**
+     * GID that corresponds to the INTERNET permission.
+     * Must match the value of AID_INET.
+     * @hide
+     */
+    public static final int INET_GID = 3003;
+
     /** {@hide} */
     public static final int NOBODY_UID = 9999;
 
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index cadae5c..754b08c 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -14952,6 +14952,21 @@
          */
         public static final String POWER_BUTTON_SUPPRESSION_DELAY_AFTER_GESTURE_WAKE =
                 "power_button_suppression_delay_after_gesture_wake";
+
+        /**
+         * For 5G NSA capable devices, determines whether NR tracking indications are on
+         * when the screen is off.
+         *
+         * Values are:
+         * 0: off - All 5G NSA tracking indications are off when the screen is off.
+         * 1: extended - All 5G NSA tracking indications are on when the screen is off as long as
+         *    the device is camped on 5G NSA (5G icon is showing in status bar).
+         *    If the device is not camped on 5G NSA, tracking indications are off.
+         * 2: always on - All 5G NSA tracking indications are on whether the screen is on or off.
+         * @hide
+         */
+        public static final String NR_NSA_TRACKING_SCREEN_OFF_MODE =
+                "nr_nsa_tracking_screen_off_mode";
     }
 
     /**
diff --git a/core/java/android/telephony/TelephonyRegistryManager.java b/core/java/android/telephony/TelephonyRegistryManager.java
index 5924421..3611d92 100644
--- a/core/java/android/telephony/TelephonyRegistryManager.java
+++ b/core/java/android/telephony/TelephonyRegistryManager.java
@@ -18,7 +18,6 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.RequiresPermission;
-import android.annotation.TestApi;
 import android.content.Context;
 import android.os.Binder;
 import android.os.RemoteException;
@@ -248,7 +247,6 @@
      * @param incomingNumber incoming phone number.
      * @hide
      */
-    @TestApi
     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
     public void notifyCallStateChangedForAllSubscriptions(@CallState int state,
             @Nullable String incomingNumber) {
diff --git a/core/java/com/android/internal/os/Zygote.java b/core/java/com/android/internal/os/Zygote.java
index f3c3ac1..2a29dfb 100644
--- a/core/java/com/android/internal/os/Zygote.java
+++ b/core/java/com/android/internal/os/Zygote.java
@@ -24,6 +24,7 @@
 import android.net.Credentials;
 import android.net.LocalServerSocket;
 import android.net.LocalSocket;
+import android.net.NetworkUtils;
 import android.os.FactoryTest;
 import android.os.IVold;
 import android.os.Process;
@@ -239,6 +240,13 @@
 
     private Zygote() {}
 
+    private static boolean containsInetGid(int[] gids) {
+        for (int i = 0; i < gids.length; i++) {
+            if (gids[i] == android.os.Process.INET_GID) return true;
+        }
+        return false;
+    }
+
     /**
      * Forks a new VM instance.  The current VM must have been started
      * with the -Xzygote flag. <b>NOTE: new instance keeps all
@@ -286,6 +294,11 @@
         if (pid == 0) {
             // Note that this event ends at the end of handleChildProc,
             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
+
+            // If no GIDs were specified, don't make any permissions changes based on groups.
+            if (gids != null && gids.length > 0) {
+                NetworkUtils.setAllowNetworkingForProcess(containsInetGid(gids));
+            }
         }
 
         // Set the Java Language thread priority to the default value for new apps.
diff --git a/core/jni/android/graphics/BitmapFactory.cpp b/core/jni/android/graphics/BitmapFactory.cpp
index f040f11..8cc1b81 100644
--- a/core/jni/android/graphics/BitmapFactory.cpp
+++ b/core/jni/android/graphics/BitmapFactory.cpp
@@ -22,7 +22,7 @@
 #include "core_jni_helpers.h"
 
 #include <HardwareBitmapUploader.h>
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <androidfw/Asset.h>
 #include <androidfw/ResourceTypes.h>
 #include <cutils/compiler.h>
diff --git a/core/jni/android_app_ActivityThread.cpp b/core/jni/android_app_ActivityThread.cpp
index fc88193..002f36c 100644
--- a/core/jni/android_app_ActivityThread.cpp
+++ b/core/jni/android_app_ActivityThread.cpp
@@ -15,8 +15,9 @@
  */
 
 #include "jni.h"
+
 #include "GraphicsJNI.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 
 #include <minikin/Layout.h>
 #include <renderthread/RenderProxy.h>
diff --git a/core/jni/android_backup_BackupDataInput.cpp b/core/jni/android_backup_BackupDataInput.cpp
index aa8acc16..79fa2a2 100644
--- a/core/jni/android_backup_BackupDataInput.cpp
+++ b/core/jni/android_backup_BackupDataInput.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "FileBackupHelper_native"
 #include <utils/Log.h>
 
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 
 #include <androidfw/BackupHelpers.h>
diff --git a/core/jni/android_backup_BackupDataOutput.cpp b/core/jni/android_backup_BackupDataOutput.cpp
index 4f5d1f80..324b3e7 100644
--- a/core/jni/android_backup_BackupDataOutput.cpp
+++ b/core/jni/android_backup_BackupDataOutput.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "FileBackupHelper_native"
 #include <utils/Log.h>
 
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include "core_jni_helpers.h"
 
 #include <androidfw/BackupHelpers.h>
diff --git a/core/jni/android_backup_BackupHelperDispatcher.cpp b/core/jni/android_backup_BackupHelperDispatcher.cpp
index fac7eba..efe7d0b 100644
--- a/core/jni/android_backup_BackupHelperDispatcher.cpp
+++ b/core/jni/android_backup_BackupHelperDispatcher.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "BackupHelperDispatcher_native"
 #include <utils/Log.h>
 
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 
 #include <sys/types.h>
diff --git a/core/jni/android_backup_FileBackupHelperBase.cpp b/core/jni/android_backup_FileBackupHelperBase.cpp
index 65840ee..5f84faf 100644
--- a/core/jni/android_backup_FileBackupHelperBase.cpp
+++ b/core/jni/android_backup_FileBackupHelperBase.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "FileBackupHelper_native"
 #include <utils/Log.h>
 
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include "core_jni_helpers.h"
 
 #include <androidfw/BackupHelpers.h>
diff --git a/core/jni/android_hardware_SerialPort.cpp b/core/jni/android_hardware_SerialPort.cpp
index 3ff2446..d06107e 100644
--- a/core/jni/android_hardware_SerialPort.cpp
+++ b/core/jni/android_hardware_SerialPort.cpp
@@ -19,7 +19,7 @@
 #include "utils/Log.h"
 
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include "core_jni_helpers.h"
 
 #include <stdio.h>
diff --git a/core/jni/android_hardware_UsbDeviceConnection.cpp b/core/jni/android_hardware_UsbDeviceConnection.cpp
index b885c28..845d65c 100644
--- a/core/jni/android_hardware_UsbDeviceConnection.cpp
+++ b/core/jni/android_hardware_UsbDeviceConnection.cpp
@@ -19,7 +19,7 @@
 #include "utils/Log.h"
 
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include "core_jni_helpers.h"
 
 #include <usbhost/usbhost.h>
diff --git a/core/jni/android_net_LocalSocketImpl.cpp b/core/jni/android_net_LocalSocketImpl.cpp
index 1163b86..42cf1f4 100644
--- a/core/jni/android_net_LocalSocketImpl.cpp
+++ b/core/jni/android_net_LocalSocketImpl.cpp
@@ -16,7 +16,7 @@
 
 #define LOG_TAG "LocalSocketImpl"
 
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include "jni.h"
 #include "utils/Log.h"
 #include "utils/misc.h"
diff --git a/core/jni/android_net_NetUtils.cpp b/core/jni/android_net_NetUtils.cpp
index 03b9793..e56809f 100644
--- a/core/jni/android_net_NetUtils.cpp
+++ b/core/jni/android_net_NetUtils.cpp
@@ -30,7 +30,7 @@
 #include <DnsProxydProtocol.h> // NETID_USE_LOCAL_NAMESERVERS
 #include <android_runtime/AndroidRuntime.h>
 #include <cutils/properties.h>
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <nativehelper/ScopedLocalRef.h>
 #include <utils/Log.h>
 #include <utils/misc.h>
@@ -226,6 +226,11 @@
             class_Network, ctor, dnsNetId & ~NETID_USE_LOCAL_NAMESERVERS, privateDnsBypass);
 }
 
+static void android_net_utils_setAllowNetworkingForProcess(JNIEnv *env, jobject thiz,
+                                                           jboolean hasConnectivity) {
+    setAllowNetworkingForProcess(hasConnectivity == JNI_TRUE);
+}
+
 static jobject android_net_utils_getTcpRepairWindow(JNIEnv *env, jobject thiz, jobject javaFd) {
     if (javaFd == NULL) {
         jniThrowNullPointerException(env, NULL);
@@ -266,6 +271,7 @@
 /*
  * JNI registration.
  */
+// clang-format off
 static const JNINativeMethod gNetworkUtilMethods[] = {
     /* name, signature, funcPtr */
     { "bindProcessToNetwork", "(I)Z", (void*) android_net_utils_bindProcessToNetwork },
@@ -282,7 +288,9 @@
     { "resNetworkResult", "(Ljava/io/FileDescriptor;)Landroid/net/DnsResolver$DnsResponse;", (void*) android_net_utils_resNetworkResult },
     { "resNetworkCancel", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_resNetworkCancel },
     { "getDnsNetwork", "()Landroid/net/Network;", (void*) android_net_utils_getDnsNetwork },
+    { "setAllowNetworkingForProcess", "(Z)V", (void *)android_net_utils_setAllowNetworkingForProcess },
 };
+// clang-format on
 
 int register_android_net_NetworkUtils(JNIEnv* env)
 {
diff --git a/core/jni/android_opengl_EGL14.cpp b/core/jni/android_opengl_EGL14.cpp
index de5e3a5..2f29cae 100644
--- a/core/jni/android_opengl_EGL14.cpp
+++ b/core/jni/android_opengl_EGL14.cpp
@@ -20,7 +20,7 @@
 #pragma GCC diagnostic ignored "-Wunused-function"
 
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/android_view_Surface.h>
 #include <android_runtime/android_graphics_SurfaceTexture.h>
diff --git a/core/jni/android_opengl_EGL15.cpp b/core/jni/android_opengl_EGL15.cpp
index 4aeed87..b9c36b9 100644
--- a/core/jni/android_opengl_EGL15.cpp
+++ b/core/jni/android_opengl_EGL15.cpp
@@ -20,7 +20,7 @@
 #pragma GCC diagnostic ignored "-Wunused-function"
 
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 
diff --git a/core/jni/android_opengl_EGLExt.cpp b/core/jni/android_opengl_EGLExt.cpp
index fef8116..1758807 100644
--- a/core/jni/android_opengl_EGLExt.cpp
+++ b/core/jni/android_opengl_EGLExt.cpp
@@ -20,7 +20,7 @@
 #pragma GCC diagnostic ignored "-Wunused-function"
 
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/android_view_Surface.h>
 #include <android_runtime/android_graphics_SurfaceTexture.h>
diff --git a/core/jni/android_opengl_GLES10.cpp b/core/jni/android_opengl_GLES10.cpp
index 3d9a3b6..e4d138d 100644
--- a/core/jni/android_opengl_GLES10.cpp
+++ b/core/jni/android_opengl_GLES10.cpp
@@ -24,7 +24,7 @@
 #include <GLES/glext.h>
 
 #include <jni.h>
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES10Ext.cpp b/core/jni/android_opengl_GLES10Ext.cpp
index 6d7f41e..3638b87 100644
--- a/core/jni/android_opengl_GLES10Ext.cpp
+++ b/core/jni/android_opengl_GLES10Ext.cpp
@@ -24,7 +24,7 @@
 #include <GLES/glext.h>
 
 #include <jni.h>
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES11.cpp b/core/jni/android_opengl_GLES11.cpp
index 39ef41a..1069a1d 100644
--- a/core/jni/android_opengl_GLES11.cpp
+++ b/core/jni/android_opengl_GLES11.cpp
@@ -24,7 +24,7 @@
 #include <GLES/glext.h>
 
 #include <jni.h>
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES11Ext.cpp b/core/jni/android_opengl_GLES11Ext.cpp
index 1144d5bf..86d7ecd 100644
--- a/core/jni/android_opengl_GLES11Ext.cpp
+++ b/core/jni/android_opengl_GLES11Ext.cpp
@@ -24,7 +24,7 @@
 #include <GLES/glext.h>
 
 #include <jni.h>
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES20.cpp b/core/jni/android_opengl_GLES20.cpp
index 2add72d..49baa51 100644
--- a/core/jni/android_opengl_GLES20.cpp
+++ b/core/jni/android_opengl_GLES20.cpp
@@ -24,7 +24,7 @@
 #include <GLES2/gl2ext.h>
 
 #include <jni.h>
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES30.cpp b/core/jni/android_opengl_GLES30.cpp
index a9c0219..32a2a24 100644
--- a/core/jni/android_opengl_GLES30.cpp
+++ b/core/jni/android_opengl_GLES30.cpp
@@ -24,7 +24,7 @@
 #include <GLES3/gl3ext.h>
 
 #include <jni.h>
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES31.cpp b/core/jni/android_opengl_GLES31.cpp
index 456da93..afe7c63 100644
--- a/core/jni/android_opengl_GLES31.cpp
+++ b/core/jni/android_opengl_GLES31.cpp
@@ -22,7 +22,7 @@
 #include <stdint.h>
 #include <GLES3/gl31.h>
 #include <jni.h>
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES31Ext.cpp b/core/jni/android_opengl_GLES31Ext.cpp
index dcaf4a5..8127433 100644
--- a/core/jni/android_opengl_GLES31Ext.cpp
+++ b/core/jni/android_opengl_GLES31Ext.cpp
@@ -23,7 +23,7 @@
 #include <GLES2/gl2ext.h>
 
 #include <jni.h>
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_opengl_GLES32.cpp b/core/jni/android_opengl_GLES32.cpp
index 6bdc711..07a794d 100644
--- a/core/jni/android_opengl_GLES32.cpp
+++ b/core/jni/android_opengl_GLES32.cpp
@@ -22,7 +22,7 @@
 #include <stdint.h>
 #include <GLES3/gl32.h>
 #include <jni.h>
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 #include <assert.h>
diff --git a/core/jni/android_os_Debug.cpp b/core/jni/android_os_Debug.cpp
index 8f9f8d2..cd36115 100644
--- a/core/jni/android_os_Debug.cpp
+++ b/core/jni/android_os_Debug.cpp
@@ -40,7 +40,7 @@
 #include <utils/misc.h>
 #include <utils/String8.h>
 
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <nativehelper/ScopedUtfChars.h>
 #include "jni.h"
 #include <dmabufinfo/dmabufinfo.h>
diff --git a/core/jni/android_os_MemoryFile.cpp b/core/jni/android_os_MemoryFile.cpp
index b21566b..8d91e63 100644
--- a/core/jni/android_os_MemoryFile.cpp
+++ b/core/jni/android_os_MemoryFile.cpp
@@ -19,7 +19,7 @@
 
 #include <cutils/ashmem.h>
 #include "core_jni_helpers.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <unistd.h>
 #include <sys/mman.h>
 
diff --git a/core/jni/android_os_Parcel.cpp b/core/jni/android_os_Parcel.cpp
index eb8d26e..7247ee0 100644
--- a/core/jni/android_os_Parcel.cpp
+++ b/core/jni/android_os_Parcel.cpp
@@ -20,7 +20,7 @@
 #include "android_os_Parcel.h"
 #include "android_util_Binder.h"
 
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 
 #include <fcntl.h>
 #include <stdio.h>
diff --git a/core/jni/android_os_SELinux.cpp b/core/jni/android_os_SELinux.cpp
index 7634547..b772dfd 100644
--- a/core/jni/android_os_SELinux.cpp
+++ b/core/jni/android_os_SELinux.cpp
@@ -21,7 +21,7 @@
 
 #include <utils/Log.h>
 
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include "jni.h"
 #include "core_jni_helpers.h"
 #include "selinux/selinux.h"
diff --git a/core/jni/android_os_SharedMemory.cpp b/core/jni/android_os_SharedMemory.cpp
index a812c35..dc86187 100644
--- a/core/jni/android_os_SharedMemory.cpp
+++ b/core/jni/android_os_SharedMemory.cpp
@@ -22,7 +22,7 @@
 #include <utils/Log.h>
 
 #include <nativehelper/jni_macros.h>
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <nativehelper/ScopedLocalRef.h>
 
 #include <algorithm>
diff --git a/core/jni/android_server_NetworkManagementSocketTagger.cpp b/core/jni/android_server_NetworkManagementSocketTagger.cpp
index 58295af..afad08a 100644
--- a/core/jni/android_server_NetworkManagementSocketTagger.cpp
+++ b/core/jni/android_server_NetworkManagementSocketTagger.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "NMST_QTagUidNative"
 #include <utils/Log.h>
 
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 
 #include "jni.h"
 #include <utils/misc.h>
diff --git a/core/jni/android_util_AssetManager.cpp b/core/jni/android_util_AssetManager.cpp
index 9342088..6fd9c7e 100644
--- a/core/jni/android_util_AssetManager.cpp
+++ b/core/jni/android_util_AssetManager.cpp
@@ -48,7 +48,7 @@
 
 #include "core_jni_helpers.h"
 #include "jni.h"
-#include "nativehelper/JNIHelp.h"
+#include "nativehelper/JNIPlatformHelp.h"
 #include "nativehelper/ScopedPrimitiveArray.h"
 #include "nativehelper/ScopedStringChars.h"
 #include "nativehelper/ScopedUtfChars.h"
diff --git a/core/jni/com_google_android_gles_jni_GLImpl.cpp b/core/jni/com_google_android_gles_jni_GLImpl.cpp
index 6b893cb..ffc1ddc 100644
--- a/core/jni/com_google_android_gles_jni_GLImpl.cpp
+++ b/core/jni/com_google_android_gles_jni_GLImpl.cpp
@@ -21,7 +21,7 @@
 #pragma GCC diagnostic ignored "-Wunused-function"
 
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <utils/misc.h>
 
diff --git a/core/jni/core_jni_helpers.h b/core/jni/core_jni_helpers.h
index f03f427..41ccd56 100644
--- a/core/jni/core_jni_helpers.h
+++ b/core/jni/core_jni_helpers.h
@@ -17,7 +17,7 @@
 #ifndef CORE_JNI_HELPERS
 #define CORE_JNI_HELPERS
 
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <nativehelper/scoped_local_ref.h>
 #include <nativehelper/scoped_utf_chars.h>
 #include <android_runtime/AndroidRuntime.h>
diff --git a/core/proto/android/providers/settings/global.proto b/core/proto/android/providers/settings/global.proto
index 829e1f7..cd4a1c8 100644
--- a/core/proto/android/providers/settings/global.proto
+++ b/core/proto/android/providers/settings/global.proto
@@ -693,6 +693,8 @@
     }
     optional Notification notification = 82;
 
+    optional SettingProto nr_nsa_tracking_screen_off_mode = 153 [ (android.privacy).dest = DEST_AUTOMATIC ];
+
     optional SettingProto nsd_on = 83 [ (android.privacy).dest = DEST_AUTOMATIC ];
 
     message Ntp {
@@ -1052,5 +1054,5 @@
 
     // Please insert fields in alphabetical order and group them into messages
     // if possible (to avoid reaching the method limit).
-    // Next tag = 151;
+    // Next tag = 154;
 }
diff --git a/core/tests/coretests/src/android/provider/SettingsBackupTest.java b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
index cb91db1..2b32040 100644
--- a/core/tests/coretests/src/android/provider/SettingsBackupTest.java
+++ b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
@@ -380,6 +380,7 @@
                     Settings.Global.NITZ_UPDATE_DIFF,
                     Settings.Global.NITZ_UPDATE_SPACING,
                     Settings.Global.NOTIFICATION_SNOOZE_OPTIONS,
+                    Settings.Global.NR_NSA_TRACKING_SCREEN_OFF_MODE,
                     Settings.Global.NSD_ON,
                     Settings.Global.NTP_SERVER,
                     Settings.Global.NTP_TIMEOUT,
diff --git a/drm/jni/android_drm_DrmManagerClient.cpp b/drm/jni/android_drm_DrmManagerClient.cpp
index 52ea8e3..e2bb6a6 100644
--- a/drm/jni/android_drm_DrmManagerClient.cpp
+++ b/drm/jni/android_drm_DrmManagerClient.cpp
@@ -19,7 +19,7 @@
 #include <utils/Log.h>
 
 #include <jni.h>
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <nativehelper/ScopedLocalRef.h>
 #include <android_runtime/AndroidRuntime.h>
 
diff --git a/identity/java/android/security/identity/IdentityCredential.java b/identity/java/android/security/identity/IdentityCredential.java
index 493c85a..4eb6e42 100644
--- a/identity/java/android/security/identity/IdentityCredential.java
+++ b/identity/java/android/security/identity/IdentityCredential.java
@@ -41,19 +41,18 @@
     /**
      * Create an ephemeral key pair to use to establish a secure channel with a reader.
      *
-     * <p>Most applications will use only the public key, and only to send it to the reader,
-     * allowing the private key to be used internally for {@link #encryptMessageToReader(byte[])}
-     * and {@link #decryptMessageFromReader(byte[])}. The private key is also provided for
-     * applications that wish to use a cipher suite that is not supported by
-     * {@link IdentityCredentialStore}.
+     * <p>Applications should use this key-pair for the communications channel with the reader
+     * using a protocol / cipher-suite appropriate for the application. One example of such a
+     * protocol is the one used for Mobile Driving Licenses, see ISO 18013-5 section 9.2.1 "Session
+     * encryption".
      *
      * @return ephemeral key pair to use to establish a secure channel with a reader.
      */
     public @NonNull abstract KeyPair createEphemeralKeyPair();
 
     /**
-     * Set the ephemeral public key provided by the reader. This must be called before
-     * {@link #encryptMessageToReader} or {@link #decryptMessageFromReader} can be called.
+     * Set the ephemeral public key provided by the reader. If called, this must be called before
+     * {@link #getEntries(byte[], Map, byte[], byte[])} is called.
      *
      * @param readerEphemeralPublicKey The ephemeral public key provided by the reader to
      *                                 establish a secure session.
@@ -65,6 +64,11 @@
     /**
      * Encrypt a message for transmission to the reader.
      *
+     * <p>Do not use. In this version of the API, this method produces an incorrect
+     * result. Instead, applications should implement message encryption/decryption themselves as
+     * detailed in the {@link #createEphemeralKeyPair()} method. In a future API-level, this
+     * method will be deprecated.
+     *
      * @param messagePlaintext unencrypted message to encrypt.
      * @return encrypted message.
      */
@@ -73,6 +77,11 @@
     /**
      * Decrypt a message received from the reader.
      *
+     * <p>Do not use. In this version of the API, this method produces an incorrect
+     * result. Instead, applications should implement message encryption/decryption themselves as
+     * detailed in the {@link #createEphemeralKeyPair()} method. In a future API-level, this
+     * method will be deprecated.
+     *
      * @param messageCiphertext encrypted message to decrypt.
      * @return decrypted message.
      * @throws MessageDecryptionException if the ciphertext couldn't be decrypted.
@@ -178,7 +187,7 @@
      *
      * <p>If {@code readerAuth} is not {@code null} it must be the bytes of a {@code COSE_Sign1}
      * structure as defined in RFC 8152. For the payload nil shall be used and the
-     * detached payload is the ReaderAuthentication CBOR described below.
+     * detached payload is the ReaderAuthenticationBytes CBOR described below.
      * <pre>
      *     ReaderAuthentication = [
      *       "ReaderAuthentication",
@@ -186,7 +195,9 @@
      *       ItemsRequestBytes
      *     ]
      *
-     *     ItemsRequestBytes = #6.24(bstr .cbor ItemsRequest)   ; Bytes of ItemsRequest
+     *     ItemsRequestBytes = #6.24(bstr .cbor ItemsRequest)
+     *
+     *     ReaderAuthenticationBytes = #6.24(bstr .cbor ReaderAuthentication)
      * </pre>
      *
      * <p>where {@code ItemsRequestBytes} are the bytes in the {@code requestMessage} parameter.
diff --git a/identity/java/android/security/identity/ResultData.java b/identity/java/android/security/identity/ResultData.java
index 37de2c4..71860d2 100644
--- a/identity/java/android/security/identity/ResultData.java
+++ b/identity/java/android/security/identity/ResultData.java
@@ -68,8 +68,8 @@
      * {@link #getMessageAuthenticationCode()} can be used to get a MAC.
      *
      * <p>The CBOR structure which is cryptographically authenticated is the
-     * {@code DeviceAuthentication} structure according to the following
-     * <a href="https://tools.ietf.org/html/draft-ietf-cbor-cddl-06">CDDL</a> schema:
+     * {@code DeviceAuthenticationBytes} structure according to the following
+     * <a href="https://tools.ietf.org/html/rfc8610">CDDL</a> schema:
      *
      * <pre>
      *   DeviceAuthentication = [
@@ -80,15 +80,9 @@
      *   ]
      *
      *   DocType = tstr
-     *
-     *   SessionTranscript = [
-     *     DeviceEngagementBytes,
-     *     EReaderKeyBytes
-     *   ]
-     *
-     *   DeviceEngagementBytes = #6.24(bstr .cbor DeviceEngagement)
-     *   EReaderKeyBytes = #6.24(bstr .cbor EReaderKey.Pub)
+     *   SessionTranscript = any
      *   DeviceNameSpacesBytes = #6.24(bstr .cbor DeviceNameSpaces)
+     *   DeviceAuthenticationBytes = #6.24(bstr .cbor DeviceAuthentication)
      * </pre>
      *
      * <p>where
@@ -115,7 +109,7 @@
     public abstract @NonNull byte[] getAuthenticatedData();
 
     /**
-     * Returns a message authentication code over the {@code DeviceAuthentication} CBOR
+     * Returns a message authentication code over the {@code DeviceAuthenticationBytes} CBOR
      * specified in {@link #getAuthenticatedData()}, to prove to the reader that the data
      * is from a trusted credential.
      *
diff --git a/media/jni/android_media_JetPlayer.cpp b/media/jni/android_media_JetPlayer.cpp
index 8a05f85..481f80b 100644
--- a/media/jni/android_media_JetPlayer.cpp
+++ b/media/jni/android_media_JetPlayer.cpp
@@ -23,7 +23,7 @@
 #include <fcntl.h>
 
 #include <jni.h>
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include "core_jni_helpers.h"
 
 #include <utils/Log.h>
diff --git a/media/jni/android_media_MediaExtractor.cpp b/media/jni/android_media_MediaExtractor.cpp
index f5ae9d0..0d395e5 100644
--- a/media/jni/android_media_MediaExtractor.cpp
+++ b/media/jni/android_media_MediaExtractor.cpp
@@ -28,7 +28,7 @@
 #include "android_runtime/Log.h"
 #include "android_util_Binder.h"
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 
 #include <android/hardware/cas/1.0/BpHwCas.h>
 #include <android/hardware/cas/1.0/BnHwCas.h>
diff --git a/media/jni/android_media_MediaMetadataRetriever.cpp b/media/jni/android_media_MediaMetadataRetriever.cpp
index a480784..91cd6d3 100644
--- a/media/jni/android_media_MediaMetadataRetriever.cpp
+++ b/media/jni/android_media_MediaMetadataRetriever.cpp
@@ -30,7 +30,7 @@
 #include <private/media/VideoFrame.h>
 
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "android_media_MediaDataSource.h"
 #include "android_media_Streams.h"
diff --git a/media/jni/android_media_MediaMuxer.cpp b/media/jni/android_media_MediaMuxer.cpp
index f0aa4c3..243ee4f 100644
--- a/media/jni/android_media_MediaMuxer.cpp
+++ b/media/jni/android_media_MediaMuxer.cpp
@@ -21,7 +21,7 @@
 #include "android_media_Streams.h"
 #include "android_runtime/AndroidRuntime.h"
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 
 #include <unistd.h>
 #include <fcntl.h>
diff --git a/media/jni/android_media_MediaPlayer.cpp b/media/jni/android_media_MediaPlayer.cpp
index ec0ce87..52e2661 100644
--- a/media/jni/android_media_MediaPlayer.cpp
+++ b/media/jni/android_media_MediaPlayer.cpp
@@ -32,7 +32,7 @@
 #include <fcntl.h>
 #include <utils/threads.h>
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/android_view_Surface.h"
 #include "android_runtime/Log.h"
diff --git a/media/jni/android_media_MediaRecorder.cpp b/media/jni/android_media_MediaRecorder.cpp
index 24fff06..a70de6d 100644
--- a/media/jni/android_media_MediaRecorder.cpp
+++ b/media/jni/android_media_MediaRecorder.cpp
@@ -37,7 +37,7 @@
 #include <nativehelper/ScopedUtfChars.h>
 
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include "android_media_AudioErrors.h"
 #include "android_media_MediaMetricsJNI.h"
 #include "android_media_MicrophoneInfo.h"
diff --git a/media/jni/android_media_MediaScanner.cpp b/media/jni/android_media_MediaScanner.cpp
index 58044c0..1fb0faa 100644
--- a/media/jni/android_media_MediaScanner.cpp
+++ b/media/jni/android_media_MediaScanner.cpp
@@ -24,7 +24,7 @@
 #include <private/media/VideoFrame.h>
 
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/Log.h"
 #include <android-base/macros.h>                // for FALLTHROUGH_INTENDED
diff --git a/media/jni/android_mtp_MtpServer.cpp b/media/jni/android_mtp_MtpServer.cpp
index 39ff04a..8a1ae92 100644
--- a/media/jni/android_mtp_MtpServer.cpp
+++ b/media/jni/android_mtp_MtpServer.cpp
@@ -25,7 +25,7 @@
 #include <utils/threads.h>
 
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "private/android_filesystem_config.h"
 
diff --git a/media/jni/soundpool/android_media_SoundPool.cpp b/media/jni/soundpool/android_media_SoundPool.cpp
index f670636..bfecd6b 100644
--- a/media/jni/soundpool/android_media_SoundPool.cpp
+++ b/media/jni/soundpool/android_media_SoundPool.cpp
@@ -21,7 +21,7 @@
 
 #include <utils/Log.h>
 #include <jni.h>
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <android_runtime/AndroidRuntime.h>
 #include "SoundPool.h"
 
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
index 65f68cc..5dc1a77 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
@@ -1074,6 +1074,10 @@
                 Settings.Global.NSD_ON,
                 GlobalSettingsProto.NSD_ON);
 
+        dumpSetting(s, p,
+                Settings.Global.NR_NSA_TRACKING_SCREEN_OFF_MODE,
+                GlobalSettingsProto.NR_NSA_TRACKING_SCREEN_OFF_MODE);
+
         final long ntpToken = p.start(GlobalSettingsProto.NTP);
         dumpSetting(s, p,
                 Settings.Global.NTP_SERVER,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
index 17481bf..c8aa22fc 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
@@ -640,8 +640,7 @@
                         + " dataState=" + state.getDataRegistrationState());
             }
             mServiceState = state;
-            // onDisplayInfoChanged is invoked directly after onServiceStateChanged, so not calling
-            // updateTelephony() to prevent icon flickering in case of overrides.
+            updateTelephony();
         }
 
         @Override
@@ -651,10 +650,6 @@
                         + " type=" + networkType);
             }
             mDataState = state;
-            if (networkType != mTelephonyDisplayInfo.getNetworkType()) {
-                mTelephonyDisplayInfo = new TelephonyDisplayInfo(networkType,
-                        TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE);
-            }
             updateTelephony();
         }
 
diff --git a/packages/Tethering/Android.bp b/packages/Tethering/Android.bp
index 4116afc..f89ee24 100644
--- a/packages/Tethering/Android.bp
+++ b/packages/Tethering/Android.bp
@@ -27,7 +27,8 @@
         "androidx.annotation_annotation",
         "netd_aidl_interface-unstable-java",
         "netlink-client",
-        "networkstack-aidl-interfaces-java",
+        // TODO: use networkstack-client instead of just including the AIDL interface
+        "networkstack-aidl-interfaces-unstable-java",
         "android.hardware.tetheroffload.config-V1.0-java",
         "android.hardware.tetheroffload.control-V1.0-java",
         "net-utils-framework-common",
diff --git a/packages/Tethering/jarjar-rules.txt b/packages/Tethering/jarjar-rules.txt
index e90a2cc..8f072e4 100644
--- a/packages/Tethering/jarjar-rules.txt
+++ b/packages/Tethering/jarjar-rules.txt
@@ -15,3 +15,6 @@
 rule android.net.LocalLog* com.android.networkstack.tethering.LocalLog@1
 
 rule android.net.shared.Inet4AddressUtils* com.android.networkstack.tethering.shared.Inet4AddressUtils@1
+
+# Classes from net-utils-framework-common
+rule com.android.net.module.util.** com.android.networkstack.tethering.util.@1
\ No newline at end of file
diff --git a/packages/Tethering/jni/android_net_util_TetheringUtils.cpp b/packages/Tethering/jni/android_net_util_TetheringUtils.cpp
index 54934406..f6eb40a 100644
--- a/packages/Tethering/jni/android_net_util_TetheringUtils.cpp
+++ b/packages/Tethering/jni/android_net_util_TetheringUtils.cpp
@@ -18,6 +18,7 @@
 #include <error.h>
 #include <jni.h>
 #include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIHelpCompat.h>
 #include <nativehelper/ScopedUtfChars.h>
 #include <net/if.h>
 #include <netinet/icmp6.h>
diff --git a/packages/Tethering/src/com/android/networkstack/tethering/OffloadHardwareInterface.java b/packages/Tethering/src/com/android/networkstack/tethering/OffloadHardwareInterface.java
index fe92204..33b9d00 100644
--- a/packages/Tethering/src/com/android/networkstack/tethering/OffloadHardwareInterface.java
+++ b/packages/Tethering/src/com/android/networkstack/tethering/OffloadHardwareInterface.java
@@ -16,8 +16,11 @@
 
 package com.android.networkstack.tethering;
 
+import static android.net.netlink.StructNlMsgHdr.NLM_F_DUMP;
+import static android.net.netlink.StructNlMsgHdr.NLM_F_REQUEST;
 import static android.net.util.TetheringUtils.uint16;
 
+import android.annotation.NonNull;
 import android.hardware.tetheroffload.config.V1_0.IOffloadConfig;
 import android.hardware.tetheroffload.control.V1_0.IOffloadControl;
 import android.hardware.tetheroffload.control.V1_0.ITetheringOffloadCallback;
@@ -25,6 +28,7 @@
 import android.hardware.tetheroffload.control.V1_0.NetworkProtocol;
 import android.hardware.tetheroffload.control.V1_0.OffloadCallbackEvent;
 import android.net.netlink.NetlinkSocket;
+import android.net.netlink.StructNlMsgHdr;
 import android.net.util.SharedLog;
 import android.net.util.SocketUtils;
 import android.os.Handler;
@@ -37,9 +41,11 @@
 import com.android.internal.annotations.VisibleForTesting;
 
 import java.io.FileDescriptor;
+import java.io.InterruptedIOException;
 import java.io.IOException;
 import java.net.SocketAddress;
 import java.net.SocketException;
+import java.nio.ByteBuffer;
 import java.util.ArrayList;
 import java.util.NoSuchElementException;
 
@@ -63,6 +69,11 @@
     private static final int NF_NETLINK_CONNTRACK_NEW = 1;
     private static final int NF_NETLINK_CONNTRACK_UPDATE = 2;
     private static final int NF_NETLINK_CONNTRACK_DESTROY = 4;
+    // Reference libnetfilter_conntrack/linux_nfnetlink_conntrack.h
+    public static final short NFNL_SUBSYS_CTNETLINK = 1;
+    public static final short IPCTNL_MSG_CT_GET = 1;
+
+    private final long NETLINK_MESSAGE_TIMEOUT_MS = 500;
 
     private final Handler mHandler;
     private final SharedLog mLog;
@@ -226,6 +237,9 @@
                 NF_NETLINK_CONNTRACK_NEW | NF_NETLINK_CONNTRACK_DESTROY);
         if (h1 == null) return false;
 
+        sendNetlinkMessage(h1, (short) ((NFNL_SUBSYS_CTNETLINK << 8) | IPCTNL_MSG_CT_GET),
+                           (short) (NLM_F_REQUEST | NLM_F_DUMP));
+
         final NativeHandle h2 = mDeps.createConntrackSocket(
                 NF_NETLINK_CONNTRACK_UPDATE | NF_NETLINK_CONNTRACK_DESTROY);
         if (h2 == null) {
@@ -252,6 +266,25 @@
         return results.mSuccess;
     }
 
+    @VisibleForTesting
+    public void sendNetlinkMessage(@NonNull NativeHandle handle, short type, short flags) {
+        final int length = StructNlMsgHdr.STRUCT_SIZE;
+        final byte[] msg = new byte[length];
+        final StructNlMsgHdr nlh = new StructNlMsgHdr();
+        final ByteBuffer byteBuffer = ByteBuffer.wrap(msg);
+        nlh.nlmsg_len = length;
+        nlh.nlmsg_type = type;
+        nlh.nlmsg_flags = flags;
+        nlh.nlmsg_seq = 1;
+        nlh.pack(byteBuffer);
+        try {
+            NetlinkSocket.sendMessage(handle.getFileDescriptor(), msg, 0 /* offset */, length,
+                                      NETLINK_MESSAGE_TIMEOUT_MS);
+        } catch (ErrnoException | InterruptedIOException e) {
+            mLog.e("Unable to send netfilter message, error: " + e);
+        }
+    }
+
     private void closeFdInNativeHandle(final NativeHandle h) {
         try {
             h.close();
diff --git a/packages/Tethering/tests/unit/src/com/android/networkstack/tethering/OffloadHardwareInterfaceTest.java b/packages/Tethering/tests/unit/src/com/android/networkstack/tethering/OffloadHardwareInterfaceTest.java
index f8ff1cb..c543fad 100644
--- a/packages/Tethering/tests/unit/src/com/android/networkstack/tethering/OffloadHardwareInterfaceTest.java
+++ b/packages/Tethering/tests/unit/src/com/android/networkstack/tethering/OffloadHardwareInterfaceTest.java
@@ -17,13 +17,17 @@
 package com.android.networkstack.tethering;
 
 import static android.net.util.TetheringUtils.uint16;
+import static android.system.OsConstants.SOCK_STREAM;
+import static android.system.OsConstants.AF_UNIX;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 import android.hardware.tetheroffload.config.V1_0.IOffloadConfig;
 import android.hardware.tetheroffload.control.V1_0.IOffloadControl;
@@ -31,11 +35,14 @@
 import android.hardware.tetheroffload.control.V1_0.NatTimeoutUpdate;
 import android.hardware.tetheroffload.control.V1_0.NetworkProtocol;
 import android.hardware.tetheroffload.control.V1_0.OffloadCallbackEvent;
+import android.net.netlink.StructNlMsgHdr;
 import android.net.util.SharedLog;
 import android.os.Handler;
 import android.os.NativeHandle;
 import android.os.test.TestLooper;
+import android.system.ErrnoException;
 import android.system.OsConstants;
+import android.system.Os;
 
 import androidx.test.filters.SmallTest;
 import androidx.test.runner.AndroidJUnit4;
@@ -47,6 +54,9 @@
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
+import java.io.FileDescriptor;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
 import java.util.ArrayList;
 
 @RunWith(AndroidJUnit4.class)
@@ -64,6 +74,10 @@
     @Mock private IOffloadControl mIOffloadControl;
     @Mock private NativeHandle mNativeHandle;
 
+    // Random values to test Netlink message.
+    private static final short TEST_TYPE = 184;
+    private static final short TEST_FLAGS = 263;
+
     class MyDependencies extends OffloadHardwareInterface.Dependencies {
         MyDependencies(SharedLog log) {
             super(log);
@@ -203,6 +217,31 @@
                 eq(uint16(udpParams.dst.port)));
     }
 
+    @Test
+    public void testNetlinkMessage() throws Exception {
+        FileDescriptor writeSocket = new FileDescriptor();
+        FileDescriptor readSocket = new FileDescriptor();
+        try {
+            Os.socketpair(AF_UNIX, SOCK_STREAM, 0, writeSocket, readSocket);
+        } catch (ErrnoException e) {
+            fail();
+            return;
+        }
+        when(mNativeHandle.getFileDescriptor()).thenReturn(writeSocket);
+
+        mOffloadHw.sendNetlinkMessage(mNativeHandle, TEST_TYPE, TEST_FLAGS);
+
+        ByteBuffer buffer = ByteBuffer.allocate(StructNlMsgHdr.STRUCT_SIZE);
+        int read = Os.read(readSocket, buffer);
+
+        buffer.flip();
+        assertEquals(StructNlMsgHdr.STRUCT_SIZE, buffer.getInt());
+        assertEquals(TEST_TYPE, buffer.getShort());
+        assertEquals(TEST_FLAGS, buffer.getShort());
+        assertEquals(1 /* seq */, buffer.getInt());
+        assertEquals(0 /* pid */, buffer.getInt());
+    }
+
     private NatTimeoutUpdate buildNatTimeoutUpdate(final int proto) {
         final NatTimeoutUpdate params = new NatTimeoutUpdate();
         params.proto = proto;
diff --git a/services/Android.bp b/services/Android.bp
index 57d9a38..581edce 100644
--- a/services/Android.bp
+++ b/services/Android.bp
@@ -111,7 +111,6 @@
         " --hide InternalClasses" + // com.android.* classes are okay in this interface
         // TODO: remove the --hide options below
         " --hide-package com.google.android.startop.iorap" +
-        " --hide ReferencesHidden" +
         " --hide DeprecationMismatch" +
         " --hide HiddenTypedefConstant",
     visibility: ["//visibility:private"],
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index 52cc8f6..e1bcb0c 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -4315,9 +4315,11 @@
         enforceInternetPermission();
         final int uid = Binder.getCallingUid();
         final int connectivityInfo = encodeBool(hasConnectivity);
-        mHandler.sendMessage(
-                mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
 
+        // Handle ConnectivityDiagnostics event before attempting to revalidate the network. This
+        // forces an ordering of ConnectivityDiagnostics events in the case where hasConnectivity
+        // does not match the known connectivity of the network - this causes NetworkMonitor to
+        // revalidate the network and generate a ConnectivityDiagnostics ConnectivityReport event.
         final NetworkAgentInfo nai;
         if (network == null) {
             nai = getDefaultNetwork();
@@ -4330,6 +4332,9 @@
                             ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
                             connectivityInfo, 0, nai));
         }
+
+        mHandler.sendMessage(
+                mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
     }
 
     private void handleReportNetworkConnectivity(
@@ -5136,14 +5141,6 @@
         }
     }
 
-    private void onPackageAdded(String packageName, int uid) {
-        if (TextUtils.isEmpty(packageName) || uid < 0) {
-            Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
-            return;
-        }
-        mPermissionMonitor.onPackageAdded(packageName, uid);
-    }
-
     private void onPackageReplaced(String packageName, int uid) {
         if (TextUtils.isEmpty(packageName) || uid < 0) {
             Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
@@ -5169,7 +5166,6 @@
             Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
             return;
         }
-        mPermissionMonitor.onPackageRemoved(uid);
 
         final int userId = UserHandle.getUserId(uid);
         synchronized (mVpns) {
@@ -5219,8 +5215,6 @@
                 onUserRemoved(userId);
             } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
                 onUserUnlocked(userId);
-            } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
-                onPackageAdded(packageName, uid);
             } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
                 onPackageReplaced(packageName, uid);
             } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
diff --git a/services/core/java/com/android/server/compat/TEST_MAPPING b/services/core/java/com/android/server/compat/TEST_MAPPING
index 0c30c79..dc1e2cb 100644
--- a/services/core/java/com/android/server/compat/TEST_MAPPING
+++ b/services/core/java/com/android/server/compat/TEST_MAPPING
@@ -15,7 +15,7 @@
         },
         // CTS tests
         {
-            "name": "CtsAppCompatHostTestCases#"
+            "name": "CtsAppCompatHostTestCases"
         }
     ]
-}
\ No newline at end of file
+}
diff --git a/services/core/java/com/android/server/connectivity/PermissionMonitor.java b/services/core/java/com/android/server/connectivity/PermissionMonitor.java
index f0b7150..c5aa8d5 100644
--- a/services/core/java/com/android/server/connectivity/PermissionMonitor.java
+++ b/services/core/java/com/android/server/connectivity/PermissionMonitor.java
@@ -72,7 +72,7 @@
  *
  * @hide
  */
-public class PermissionMonitor {
+public class PermissionMonitor implements PackageManagerInternal.PackageListObserver {
     private static final String TAG = "PermissionMonitor";
     private static final boolean DBG = true;
     protected static final Boolean SYSTEM = Boolean.TRUE;
@@ -102,44 +102,6 @@
     @GuardedBy("this")
     private final Set<Integer> mAllApps = new HashSet<>();
 
-    private class PackageListObserver implements PackageManagerInternal.PackageListObserver {
-
-        private int getPermissionForUid(int uid) {
-            int permission = 0;
-            // Check all the packages for this UID. The UID has the permission if any of the
-            // packages in it has the permission.
-            String[] packages = mPackageManager.getPackagesForUid(uid);
-            if (packages != null && packages.length > 0) {
-                for (String name : packages) {
-                    final PackageInfo app = getPackageInfo(name);
-                    if (app != null && app.requestedPermissions != null) {
-                        permission |= getNetdPermissionMask(app.requestedPermissions,
-                              app.requestedPermissionsFlags);
-                    }
-                }
-            } else {
-                // The last package of this uid is removed from device. Clean the package up.
-                permission = INetd.PERMISSION_UNINSTALLED;
-            }
-            return permission;
-        }
-
-        @Override
-        public void onPackageAdded(String packageName, int uid) {
-            sendPackagePermissionsForUid(uid, getPermissionForUid(uid));
-        }
-
-        @Override
-        public void onPackageChanged(@NonNull String packageName, int uid) {
-            sendPackagePermissionsForUid(uid, getPermissionForUid(uid));
-        }
-
-        @Override
-        public void onPackageRemoved(String packageName, int uid) {
-            sendPackagePermissionsForUid(uid, getPermissionForUid(uid));
-        }
-    }
-
     public PermissionMonitor(Context context, INetd netd) {
         mPackageManager = context.getPackageManager();
         mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
@@ -153,7 +115,7 @@
 
         PackageManagerInternal pmi = LocalServices.getService(PackageManagerInternal.class);
         if (pmi != null) {
-            pmi.getPackageList(new PackageListObserver());
+            pmi.getPackageList(this);
         } else {
             loge("failed to get the PackageManagerInternal service");
         }
@@ -363,15 +325,38 @@
         return currentPermission;
     }
 
+    private int getPermissionForUid(final int uid) {
+        int permission = INetd.PERMISSION_NONE;
+        // Check all the packages for this UID. The UID has the permission if any of the
+        // packages in it has the permission.
+        final String[] packages = mPackageManager.getPackagesForUid(uid);
+        if (packages != null && packages.length > 0) {
+            for (String name : packages) {
+                final PackageInfo app = getPackageInfo(name);
+                if (app != null && app.requestedPermissions != null) {
+                    permission |= getNetdPermissionMask(app.requestedPermissions,
+                            app.requestedPermissionsFlags);
+                }
+            }
+        } else {
+            // The last package of this uid is removed from device. Clean the package up.
+            permission = INetd.PERMISSION_UNINSTALLED;
+        }
+        return permission;
+    }
+
     /**
-     * Called when a package is added. See {link #ACTION_PACKAGE_ADDED}.
+     * Called when a package is added.
      *
      * @param packageName The name of the new package.
      * @param uid The uid of the new package.
      *
      * @hide
      */
-    public synchronized void onPackageAdded(String packageName, int uid) {
+    @Override
+    public synchronized void onPackageAdded(@NonNull final String packageName, final int uid) {
+        sendPackagePermissionsForUid(uid, getPermissionForUid(uid));
+
         // If multiple packages share a UID (cf: android:sharedUserId) and ask for different
         // permissions, don't downgrade (i.e., if it's already SYSTEM, leave it as is).
         final Boolean permission = highestPermissionForUid(mApps.get(uid), packageName);
@@ -398,13 +383,17 @@
     }
 
     /**
-     * Called when a package is removed. See {link #ACTION_PACKAGE_REMOVED}.
+     * Called when a package is removed.
      *
+     * @param packageName The name of the removed package or null.
      * @param uid containing the integer uid previously assigned to the package.
      *
      * @hide
      */
-    public synchronized void onPackageRemoved(int uid) {
+    @Override
+    public synchronized void onPackageRemoved(@NonNull final String packageName, final int uid) {
+        sendPackagePermissionsForUid(uid, getPermissionForUid(uid));
+
         // If the newly-removed package falls within some VPN's uid range, update Netd with it.
         // This needs to happen before the mApps update below, since removeBypassingUids() depends
         // on mApps to check if the package can bypass VPN.
@@ -449,6 +438,19 @@
         }
     }
 
+    /**
+     * Called when a package is changed.
+     *
+     * @param packageName The name of the changed package.
+     * @param uid The uid of the changed package.
+     *
+     * @hide
+     */
+    @Override
+    public synchronized void onPackageChanged(@NonNull final String packageName, final int uid) {
+        sendPackagePermissionsForUid(uid, getPermissionForUid(uid));
+    }
+
     private static int getNetdPermissionMask(String[] requestedPermissions,
                                              int[] requestedPermissionsFlags) {
         int permissions = 0;
diff --git a/services/core/jni/com_android_server_AlarmManagerService.cpp b/services/core/jni/com_android_server_AlarmManagerService.cpp
index a99c0a3..335040a 100644
--- a/services/core/jni/com_android_server_AlarmManagerService.cpp
+++ b/services/core/jni/com_android_server_AlarmManagerService.cpp
@@ -1,5 +1,4 @@
-/* //device/libs/android_runtime/android_server_AlarmManagerService.cpp
-**
+/*
 ** Copyright 2006, The Android Open Source Project
 **
 ** Licensed under the Apache License, Version 2.0 (the "License");
@@ -19,6 +18,8 @@
 
 #include <nativehelper/JNIHelp.h>
 #include "jni.h"
+#include <android-base/file.h>
+#include <android-base/unique_fd.h>
 #include <utils/Log.h>
 #include <utils/misc.h>
 #include <utils/String8.h>
@@ -75,8 +76,8 @@
 class AlarmImpl
 {
 public:
-    AlarmImpl(const TimerFds &fds, int epollfd, int rtc_id) :
-        fds{fds}, epollfd{epollfd}, rtc_id{rtc_id} { }
+    AlarmImpl(const TimerFds &fds, int epollfd, const std::string& rtc_dev) :
+        fds{fds}, epollfd{epollfd}, rtc_dev{rtc_dev} { }
     ~AlarmImpl();
 
     int set(int type, struct timespec *ts);
@@ -87,7 +88,7 @@
 private:
     const TimerFds fds;
     const int epollfd;
-    const int rtc_id;
+    std::string rtc_dev;
 };
 
 AlarmImpl::~AlarmImpl()
@@ -132,38 +133,24 @@
 
 int AlarmImpl::setTime(struct timeval *tv)
 {
-    struct rtc_time rtc;
-    struct tm tm, *gmtime_res;
-    int fd;
-    int res;
-
-    res = settimeofday(tv, NULL);
-    if (res < 0) {
-        ALOGV("settimeofday() failed: %s\n", strerror(errno));
+    if (settimeofday(tv, NULL) == -1) {
+        ALOGV("settimeofday() failed: %s", strerror(errno));
         return -1;
     }
 
-    if (rtc_id < 0) {
-        ALOGV("Not setting RTC because wall clock RTC was not found");
-        errno = ENODEV;
+    android::base::unique_fd fd{open(rtc_dev.c_str(), O_RDWR)};
+    if (!fd.ok()) {
+        ALOGE("Unable to open %s: %s", rtc_dev.c_str(), strerror(errno));
         return -1;
     }
 
-    android::String8 rtc_dev = String8::format("/dev/rtc%d", rtc_id);
-    fd = open(rtc_dev.string(), O_RDWR);
-    if (fd < 0) {
-        ALOGV("Unable to open %s: %s\n", rtc_dev.string(), strerror(errno));
-        return res;
+    struct tm tm;
+    if (!gmtime_r(&tv->tv_sec, &tm)) {
+        ALOGV("gmtime_r() failed: %s", strerror(errno));
+        return -1;
     }
 
-    gmtime_res = gmtime_r(&tv->tv_sec, &tm);
-    if (!gmtime_res) {
-        ALOGV("gmtime_r() failed: %s\n", strerror(errno));
-        res = -1;
-        goto done;
-    }
-
-    memset(&rtc, 0, sizeof(rtc));
+    struct rtc_time rtc = {};
     rtc.tm_sec = tm.tm_sec;
     rtc.tm_min = tm.tm_min;
     rtc.tm_hour = tm.tm_hour;
@@ -173,12 +160,12 @@
     rtc.tm_wday = tm.tm_wday;
     rtc.tm_yday = tm.tm_yday;
     rtc.tm_isdst = tm.tm_isdst;
-    res = ioctl(fd, RTC_SET_TIME, &rtc);
-    if (res < 0)
-        ALOGV("RTC_SET_TIME ioctl failed: %s\n", strerror(errno));
-done:
-    close(fd);
-    return res;
+    if (ioctl(fd, RTC_SET_TIME, &rtc) == -1) {
+        ALOGV("RTC_SET_TIME ioctl failed: %s", strerror(errno));
+        return -1;
+    }
+
+    return 0;
 }
 
 int AlarmImpl::waitForAlarm()
@@ -251,65 +238,6 @@
     return 0;
 }
 
-static const char rtc_sysfs[] = "/sys/class/rtc";
-
-static bool rtc_is_hctosys(unsigned int rtc_id)
-{
-    android::String8 hctosys_path = String8::format("%s/rtc%u/hctosys",
-            rtc_sysfs, rtc_id);
-    FILE *file = fopen(hctosys_path.string(), "re");
-    if (!file) {
-        ALOGE("failed to open %s: %s", hctosys_path.string(), strerror(errno));
-        return false;
-    }
-
-    unsigned int hctosys;
-    bool ret = false;
-    int err = fscanf(file, "%u", &hctosys);
-    if (err == EOF)
-        ALOGE("failed to read from %s: %s", hctosys_path.string(),
-                strerror(errno));
-    else if (err == 0)
-        ALOGE("%s did not have expected contents", hctosys_path.string());
-    else
-        ret = hctosys;
-
-    fclose(file);
-    return ret;
-}
-
-static int wall_clock_rtc()
-{
-    std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir(rtc_sysfs), closedir);
-    if (!dir.get()) {
-        ALOGE("failed to open %s: %s", rtc_sysfs, strerror(errno));
-        return -1;
-    }
-
-    struct dirent *dirent;
-    while (errno = 0, dirent = readdir(dir.get())) {
-        unsigned int rtc_id;
-        int matched = sscanf(dirent->d_name, "rtc%u", &rtc_id);
-
-        if (matched < 0)
-            break;
-        else if (matched != 1)
-            continue;
-
-        if (rtc_is_hctosys(rtc_id)) {
-            ALOGV("found wall clock RTC %u", rtc_id);
-            return rtc_id;
-        }
-    }
-
-    if (errno == 0)
-        ALOGW("no wall clock RTC found");
-    else
-        ALOGE("failed to enumerate RTCs: %s", strerror(errno));
-
-    return -1;
-}
-
 static void log_timerfd_create_error(clockid_t id)
 {
     if (errno == EINVAL) {
@@ -343,8 +271,7 @@
 
     epollfd = epoll_create(fds.size());
     if (epollfd < 0) {
-        ALOGE("epoll_create(%zu) failed: %s", fds.size(),
-                strerror(errno));
+        ALOGE("epoll_create(%zu) failed: %s", fds.size(), strerror(errno));
         return 0;
     }
 
@@ -360,7 +287,19 @@
         }
     }
 
-    AlarmImpl *ret = new AlarmImpl(fds, epollfd, wall_clock_rtc());
+    // Find the wall clock RTC. We expect this always to be /dev/rtc0, but
+    // check the /dev/rtc symlink first so that legacy devices that don't use
+    // rtc0 can add a symlink rather than need to carry a local patch to this
+    // code.
+    //
+    // TODO: if you're reading this in a world where all devices are using the
+    // GKI, you can remove the readlink and just assume /dev/rtc0.
+    std::string dev_rtc;
+    if (!android::base::Readlink("/dev/rtc", &dev_rtc)) {
+        dev_rtc = "/dev/rtc0";
+    }
+
+    std::unique_ptr<AlarmImpl> alarm{new AlarmImpl(fds, epollfd, dev_rtc)};
 
     for (size_t i = 0; i < fds.size(); i++) {
         epoll_event event;
@@ -370,13 +309,11 @@
         int err = epoll_ctl(epollfd, EPOLL_CTL_ADD, fds[i], &event);
         if (err < 0) {
             ALOGE("epoll_ctl(EPOLL_CTL_ADD) failed: %s", strerror(errno));
-            delete ret;
             return 0;
         }
     }
 
-    struct itimerspec spec;
-    memset(&spec, 0, sizeof(spec));
+    struct itimerspec spec = {};
     /* 0 = disarmed; the timerfd doesn't need to be armed to get
        RTC change notifications, just set up as cancelable */
 
@@ -384,11 +321,10 @@
             TFD_TIMER_ABSTIME | TFD_TIMER_CANCEL_ON_SET, &spec, NULL);
     if (err < 0) {
         ALOGE("timerfd_settime() failed: %s", strerror(errno));
-        delete ret;
         return 0;
     }
 
-    return reinterpret_cast<jlong>(ret);
+    return reinterpret_cast<jlong>(alarm.release());
 }
 
 static jlong android_server_AlarmManagerService_getNextAlarm(JNIEnv*, jobject, jlong nativeData, jint type)
diff --git a/services/core/jni/com_android_server_SerialService.cpp b/services/core/jni/com_android_server_SerialService.cpp
index c945999..6600c98 100644
--- a/services/core/jni/com_android_server_SerialService.cpp
+++ b/services/core/jni/com_android_server_SerialService.cpp
@@ -18,7 +18,7 @@
 #include "utils/Log.h"
 
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 
 #include <sys/types.h>
diff --git a/services/core/jni/com_android_server_UsbDeviceManager.cpp b/services/core/jni/com_android_server_UsbDeviceManager.cpp
index 72dce4d..3ab5920 100644
--- a/services/core/jni/com_android_server_UsbDeviceManager.cpp
+++ b/services/core/jni/com_android_server_UsbDeviceManager.cpp
@@ -18,7 +18,7 @@
 #include "utils/Log.h"
 
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <nativehelper/ScopedUtfChars.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/Log.h"
diff --git a/services/core/jni/com_android_server_UsbHostManager.cpp b/services/core/jni/com_android_server_UsbHostManager.cpp
index a40bcd0..a629b69 100644
--- a/services/core/jni/com_android_server_UsbHostManager.cpp
+++ b/services/core/jni/com_android_server_UsbHostManager.cpp
@@ -18,7 +18,7 @@
 #include "utils/Log.h"
 
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/Log.h"
 
diff --git a/services/core/jni/com_android_server_UsbMidiDevice.cpp b/services/core/jni/com_android_server_UsbMidiDevice.cpp
index 8ac2c4f..d6b5bed 100644
--- a/services/core/jni/com_android_server_UsbMidiDevice.cpp
+++ b/services/core/jni/com_android_server_UsbMidiDevice.cpp
@@ -19,7 +19,7 @@
 #include "utils/Log.h"
 
 #include "jni.h"
-#include <nativehelper/JNIHelp.h>
+#include <nativehelper/JNIPlatformHelp.h>
 #include <nativehelper/ScopedLocalRef.h>
 #include "android_runtime/AndroidRuntime.h"
 #include "android_runtime/Log.h"
diff --git a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
index 9a47ae1..0965249 100644
--- a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
+++ b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
@@ -273,6 +273,11 @@
     boolean setDefaultDialer(in String packageName);
 
     /**
+     * Stop suppressing blocked numbers after a call to emergency services. Shell only.
+     */
+    void stopBlockSuppression();
+
+    /**
     * @see TelecomServiceImpl#createManageBlockedNumbersIntent
     **/
     Intent createManageBlockedNumbersIntent();
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index 0690a90..d319e37 100644
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -560,6 +560,15 @@
     public static final String KEY_CARRIER_VT_AVAILABLE_BOOL = "carrier_vt_available_bool";
 
     /**
+     * Flag specifying whether to show an alert dialog for 5G disable when the user disables VoLTE.
+     * By default this value is {@code false}.
+     *
+     * @hide
+     */
+    public static final String KEY_VOLTE_5G_LIMITED_ALERT_DIALOG_BOOL =
+            "volte_5g_limited_alert_dialog_bool";
+
+    /**
      * Flag specifying whether the carrier wants to notify the user when a VT call has been handed
      * over from WIFI to LTE.
      * <p>
@@ -1405,6 +1414,14 @@
     public static final String KEY_CARRIER_NAME_STRING = "carrier_name_string";
 
     /**
+     * To override wifi calling's carrier name string using ef_pnn from sim card when SPN in empty.
+     *
+     * @hide
+     */
+    public static final String KEY_WFC_CARRIER_NAME_OVERRIDE_BY_PNN_BOOL =
+            "wfc_carrier_name_override_by_pnn_bool";
+
+    /**
      * Override the SPN Display Condition 2 integer bits (lsb). B2, B1 is the last two bits of the
      * spn display condition coding.
      *
@@ -3781,6 +3798,7 @@
         sDefaults.putBoolean(KEY_CARRIER_SETTINGS_ENABLE_BOOL, false);
         sDefaults.putBoolean(KEY_CARRIER_VOLTE_AVAILABLE_BOOL, false);
         sDefaults.putBoolean(KEY_CARRIER_VT_AVAILABLE_BOOL, false);
+        sDefaults.putBoolean(KEY_VOLTE_5G_LIMITED_ALERT_DIALOG_BOOL, false);
         sDefaults.putBoolean(KEY_NOTIFY_HANDOVER_VIDEO_FROM_WIFI_TO_LTE_BOOL, false);
         sDefaults.putBoolean(KEY_ALLOW_MERGING_RTT_CALLS_BOOL, false);
         sDefaults.putBoolean(KEY_NOTIFY_HANDOVER_VIDEO_FROM_LTE_TO_WIFI_BOOL, false);
@@ -3960,6 +3978,7 @@
         sDefaults.putBoolean(KEY_CONFIG_WIFI_DISABLE_IN_ECBM, false);
         sDefaults.putBoolean(KEY_CARRIER_NAME_OVERRIDE_BOOL, false);
         sDefaults.putString(KEY_CARRIER_NAME_STRING, "");
+        sDefaults.putBoolean(KEY_WFC_CARRIER_NAME_OVERRIDE_BY_PNN_BOOL, false);
         sDefaults.putInt(KEY_SPN_DISPLAY_CONDITION_OVERRIDE_INT, -1);
         sDefaults.putStringArray(KEY_SPDI_OVERRIDE_STRING_ARRAY, null);
         sDefaults.putStringArray(KEY_PNN_OVERRIDE_STRING_ARRAY, null);
diff --git a/telephony/java/android/telephony/TelephonyScanManager.java b/telephony/java/android/telephony/TelephonyScanManager.java
index 359d08d..3f8fd9d 100644
--- a/telephony/java/android/telephony/TelephonyScanManager.java
+++ b/telephony/java/android/telephony/TelephonyScanManager.java
@@ -31,6 +31,7 @@
 import android.os.ServiceManager;
 import android.util.SparseArray;
 
+import com.android.internal.annotations.GuardedBy;
 import com.android.internal.telephony.ITelephony;
 import com.android.telephony.Rlog;
 
@@ -56,6 +57,8 @@
     public static final int CALLBACK_SCAN_COMPLETE = 3;
     /** @hide */
     public static final int CALLBACK_RESTRICTED_SCAN_RESULTS = 4;
+    /** @hide */
+    public static final int CALLBACK_TELEPHONY_DIED = 5;
 
     /** @hide */
     public static final int INVALID_SCAN_ID = -1;
@@ -104,17 +107,44 @@
     }
 
     private final Looper mLooper;
+    private final Handler mHandler;
     private final Messenger mMessenger;
     private final SparseArray<NetworkScanInfo> mScanInfo = new SparseArray<NetworkScanInfo>();
+    private final Binder.DeathRecipient mDeathRecipient;
 
     public TelephonyScanManager() {
         HandlerThread thread = new HandlerThread(TAG);
         thread.start();
         mLooper = thread.getLooper();
-        mMessenger = new Messenger(new Handler(mLooper) {
+        mHandler = new Handler(mLooper) {
             @Override
             public void handleMessage(Message message) {
                 checkNotNull(message, "message cannot be null");
+                if (message.what == CALLBACK_TELEPHONY_DIED) {
+                    // If there are no objects in mScanInfo then binder death will simply return.
+                    synchronized (mScanInfo) {
+                        for (int i = 0; i < mScanInfo.size(); i++) {
+                            NetworkScanInfo nsi = mScanInfo.valueAt(i);
+                            // At this point we go into panic mode and ignore errors that would
+                            // normally stop the show in order to try and clean up as gracefully
+                            // as possible.
+                            if (nsi == null) continue; // shouldn't be possible
+                            Executor e = nsi.mExecutor;
+                            NetworkScanCallback cb = nsi.mCallback;
+                            if (e == null || cb == null) continue;
+                            try {
+                                e.execute(
+                                        () -> cb.onError(NetworkScan.ERROR_MODEM_UNAVAILABLE));
+                            } catch (java.util.concurrent.RejectedExecutionException ignore) {
+                                // ignore so that we can continue
+                            }
+                        }
+
+                        mScanInfo.clear();
+                    }
+                    return;
+                }
+
                 NetworkScanInfo nsi;
                 synchronized (mScanInfo) {
                     nsi = mScanInfo.get(message.arg2);
@@ -159,6 +189,9 @@
                                 Rlog.d(TAG, "onError: " + errorCode);
                                 callback.onError(errorCode);
                             });
+                            synchronized (mScanInfo) {
+                                mScanInfo.remove(message.arg2);
+                            }
                         } catch (Exception e) {
                             Rlog.e(TAG, "Exception in networkscan callback onError", e);
                         }
@@ -169,7 +202,9 @@
                                 Rlog.d(TAG, "onComplete");
                                 callback.onComplete();
                             });
-                            mScanInfo.remove(message.arg2);
+                            synchronized (mScanInfo) {
+                                mScanInfo.remove(message.arg2);
+                            }
                         } catch (Exception e) {
                             Rlog.e(TAG, "Exception in networkscan callback onComplete", e);
                         }
@@ -179,7 +214,14 @@
                         break;
                 }
             }
-        });
+        };
+        mMessenger = new Messenger(mHandler);
+        mDeathRecipient = new Binder.DeathRecipient() {
+            @Override
+            public void binderDied() {
+                mHandler.obtainMessage(CALLBACK_TELEPHONY_DIED).sendToTarget();
+            }
+        };
     }
 
     /**
@@ -190,7 +232,7 @@
      *
      * <p>
      * Requires Permission:
-     * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} and
+     * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and
      *   {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
      * Or the calling app has carrier privileges. @see #hasCarrierPrivileges
      *
@@ -203,19 +245,26 @@
             NetworkScanRequest request, Executor executor, NetworkScanCallback callback,
             String callingPackage, String callingFeatureId) {
         try {
-            ITelephony telephony = getITelephony();
-            if (telephony != null) {
-                synchronized (mScanInfo) {
-                    int scanId = telephony.requestNetworkScan(
-                            subId, request, mMessenger, new Binder(), callingPackage,
-                            callingFeatureId);
-                    if (scanId == INVALID_SCAN_ID) {
-                        Rlog.e(TAG, "Failed to initiate network scan");
-                        return null;
-                    }
-                    saveScanInfo(scanId, request, executor, callback);
-                    return new NetworkScan(scanId, subId);
-                }
+            final ITelephony telephony = getITelephony();
+            if (telephony == null) return null;
+
+            int scanId = telephony.requestNetworkScan(
+                    subId, request, mMessenger, new Binder(), callingPackage,
+                    callingFeatureId);
+            if (scanId == INVALID_SCAN_ID) {
+                Rlog.e(TAG, "Failed to initiate network scan");
+                return null;
+            }
+            synchronized (mScanInfo) {
+                // We link to death whenever a scan is started to ensure that we are linked
+                // at the point that phone process death might matter.
+                // We never unlink because:
+                // - Duplicate links to death with the same callback do not result in
+                //   extraneous callbacks (the tracking de-dupes).
+                // - Receiving binderDeath() when no scans are active is a no-op.
+                telephony.asBinder().linkToDeath(mDeathRecipient, 0);
+                saveScanInfo(scanId, request, executor, callback);
+                return new NetworkScan(scanId, subId);
             }
         } catch (RemoteException ex) {
             Rlog.e(TAG, "requestNetworkScan RemoteException", ex);
@@ -225,6 +274,7 @@
         return null;
     }
 
+    @GuardedBy("mScanInfo")
     private void saveScanInfo(
             int id, NetworkScanRequest request, Executor executor, NetworkScanCallback callback) {
         mScanInfo.put(id, new NetworkScanInfo(request, executor, callback));
diff --git a/telephony/java/android/telephony/ims/feature/MmTelFeature.java b/telephony/java/android/telephony/ims/feature/MmTelFeature.java
index 6840e8e..5ee6ec9 100644
--- a/telephony/java/android/telephony/ims/feature/MmTelFeature.java
+++ b/telephony/java/android/telephony/ims/feature/MmTelFeature.java
@@ -346,7 +346,6 @@
          * @hide
          */
         @Override
-        @SystemApi @TestApi
         public void onIncomingCall(IImsCallSession c, Bundle extras) {
 
         }
@@ -358,7 +357,6 @@
          * @hide
          */
         @Override
-        @SystemApi @TestApi
         public void onRejectedCall(ImsCallProfile callProfile, ImsReasonInfo reason) {
 
         }
@@ -369,7 +367,6 @@
          * @hide
          */
         @Override
-        @SystemApi @TestApi
         public void onVoiceMessageCountUpdate(int count) {
 
         }
diff --git a/test-base/Android.bp b/test-base/Android.bp
index 69c296e..c7c9fc7 100644
--- a/test-base/Android.bp
+++ b/test-base/Android.bp
@@ -38,6 +38,7 @@
     ],
 
     compile_dex: true,
+    default_to_stubs: true,
 }
 
 // Build the android.test.base_static library
diff --git a/test-mock/Android.bp b/test-mock/Android.bp
index 248c117..7d0f92f 100644
--- a/test-mock/Android.bp
+++ b/test-mock/Android.bp
@@ -37,6 +37,7 @@
         "android.test.mock",
     ],
     compile_dex: true,
+    default_to_stubs: true,
 }
 
 // Make the current.txt available for use by the cts/tests/signature tests.
diff --git a/test-mock/src/android/test/mock/MockContentProvider.java b/test-mock/src/android/test/mock/MockContentProvider.java
index e9a5ff7..3206adc 100644
--- a/test-mock/src/android/test/mock/MockContentProvider.java
+++ b/test-mock/src/android/test/mock/MockContentProvider.java
@@ -29,6 +29,7 @@
 import android.content.res.AssetFileDescriptor;
 import android.database.Cursor;
 import android.net.Uri;
+import android.os.Binder;
 import android.os.Bundle;
 import android.os.IBinder;
 import android.os.ICancellationSignal;
@@ -282,7 +283,7 @@
      * @hide
      */
     public IBinder getIContentProviderBinder() {
-        throw new UnsupportedOperationException("unimplemented mock method");
+        return new Binder();
     }
 
     /**
diff --git a/test-runner/Android.bp b/test-runner/Android.bp
index 75f5b5a..1f6db84 100644
--- a/test-runner/Android.bp
+++ b/test-runner/Android.bp
@@ -41,6 +41,7 @@
     ],
 
     compile_dex: true,
+    default_to_stubs: true,
 }
 
 // Build the android.test.runner-minus-junit library
diff --git a/test-runner/api/current.txt b/test-runner/api/current.txt
index 2c19a2e..5407b68 100644
--- a/test-runner/api/current.txt
+++ b/test-runner/api/current.txt
@@ -78,6 +78,7 @@
 
   @Deprecated public class InstrumentationTestRunner extends android.app.Instrumentation implements android.test.TestSuiteProvider {
     ctor @Deprecated public InstrumentationTestRunner();
+    method @Deprecated protected void addTestListener(junit.framework.TestListener);
     method @Deprecated public junit.framework.TestSuite getAllTests();
     method @Deprecated protected android.test.AndroidTestRunner getAndroidTestRunner();
     method @Deprecated public android.os.Bundle getArguments();
diff --git a/test-runner/src/android/test/InstrumentationTestRunner.java b/test-runner/src/android/test/InstrumentationTestRunner.java
index b2582c1..07e3f87 100644
--- a/test-runner/src/android/test/InstrumentationTestRunner.java
+++ b/test-runner/src/android/test/InstrumentationTestRunner.java
@@ -410,7 +410,6 @@
 
     /**
      * Add a {@link TestListener}
-     * @hide
      */
     protected void addTestListener(TestListener listener){
         if(mTestRunner!=null && listener!=null){
diff --git a/tests/net/java/android/net/DnsPacketTest.java b/tests/net/java/android/net/DnsPacketTest.java
deleted file mode 100644
index 975abf4..0000000
--- a/tests/net/java/android/net/DnsPacketTest.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.net;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.Arrays;
-import java.util.List;
-
-@RunWith(AndroidJUnit4.class)
-@SmallTest
-public class DnsPacketTest {
-    private void assertHeaderParses(DnsPacket.DnsHeader header, int id, int flag,
-            int qCount, int aCount, int nsCount, int arCount) {
-        assertEquals(header.id, id);
-        assertEquals(header.flags, flag);
-        assertEquals(header.getRecordCount(DnsPacket.QDSECTION), qCount);
-        assertEquals(header.getRecordCount(DnsPacket.ANSECTION), aCount);
-        assertEquals(header.getRecordCount(DnsPacket.NSSECTION), nsCount);
-        assertEquals(header.getRecordCount(DnsPacket.ARSECTION), arCount);
-    }
-
-    private void assertRecordParses(DnsPacket.DnsRecord record, String dname,
-            int dtype, int dclass, int ttl, byte[] rr) {
-        assertEquals(record.dName, dname);
-        assertEquals(record.nsType, dtype);
-        assertEquals(record.nsClass, dclass);
-        assertEquals(record.ttl, ttl);
-        assertTrue(Arrays.equals(record.getRR(), rr));
-    }
-
-    class TestDnsPacket extends DnsPacket {
-        TestDnsPacket(byte[] data) throws ParseException {
-            super(data);
-        }
-
-        public DnsHeader getHeader() {
-            return mHeader;
-        }
-        public List<DnsRecord> getRecordList(int secType) {
-            return mRecords[secType];
-        }
-    }
-
-    @Test
-    public void testNullDisallowed() {
-        try {
-            new TestDnsPacket(null);
-            fail("Exception not thrown for null byte array");
-        } catch (ParseException e) {
-        }
-    }
-
-    @Test
-    public void testV4Answer() throws Exception {
-        final byte[] v4blob = new byte[] {
-            /* Header */
-            0x55, 0x66, /* Transaction ID */
-            (byte) 0x81, (byte) 0x80, /* Flags */
-            0x00, 0x01, /* Questions */
-            0x00, 0x01, /* Answer RRs */
-            0x00, 0x00, /* Authority RRs */
-            0x00, 0x00, /* Additional RRs */
-            /* Queries */
-            0x03, 0x77, 0x77, 0x77, 0x06, 0x67, 0x6F, 0x6F, 0x67, 0x6c, 0x65,
-            0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */
-            0x00, 0x01, /* Type */
-            0x00, 0x01, /* Class */
-            /* Answers */
-            (byte) 0xc0, 0x0c, /* Name */
-            0x00, 0x01, /* Type */
-            0x00, 0x01, /* Class */
-            0x00, 0x00, 0x01, 0x2b, /* TTL */
-            0x00, 0x04, /* Data length */
-            (byte) 0xac, (byte) 0xd9, (byte) 0xa1, (byte) 0x84 /* Address */
-        };
-        TestDnsPacket packet = new TestDnsPacket(v4blob);
-
-        // Header part
-        assertHeaderParses(packet.getHeader(), 0x5566, 0x8180, 1, 1, 0, 0);
-
-        // Record part
-        List<DnsPacket.DnsRecord> qdRecordList =
-                packet.getRecordList(DnsPacket.QDSECTION);
-        assertEquals(qdRecordList.size(), 1);
-        assertRecordParses(qdRecordList.get(0), "www.google.com", 1, 1, 0, null);
-
-        List<DnsPacket.DnsRecord> anRecordList =
-                packet.getRecordList(DnsPacket.ANSECTION);
-        assertEquals(anRecordList.size(), 1);
-        assertRecordParses(anRecordList.get(0), "www.google.com", 1, 1, 0x12b,
-                new byte[]{ (byte) 0xac, (byte) 0xd9, (byte) 0xa1, (byte) 0x84 });
-    }
-
-    @Test
-    public void testV6Answer() throws Exception {
-        final byte[] v6blob = new byte[] {
-            /* Header */
-            0x77, 0x22, /* Transaction ID */
-            (byte) 0x81, (byte) 0x80, /* Flags */
-            0x00, 0x01, /* Questions */
-            0x00, 0x01, /* Answer RRs */
-            0x00, 0x00, /* Authority RRs */
-            0x00, 0x00, /* Additional RRs */
-            /* Queries */
-            0x03, 0x77, 0x77, 0x77, 0x06, 0x67, 0x6F, 0x6F, 0x67, 0x6c, 0x65,
-            0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */
-            0x00, 0x1c, /* Type */
-            0x00, 0x01, /* Class */
-            /* Answers */
-            (byte) 0xc0, 0x0c, /* Name */
-            0x00, 0x1c, /* Type */
-            0x00, 0x01, /* Class */
-            0x00, 0x00, 0x00, 0x37, /* TTL */
-            0x00, 0x10, /* Data length */
-            0x24, 0x04, 0x68, 0x00, 0x40, 0x05, 0x08, 0x0d,
-            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x04 /* Address */
-        };
-        TestDnsPacket packet = new TestDnsPacket(v6blob);
-
-        // Header part
-        assertHeaderParses(packet.getHeader(), 0x7722, 0x8180, 1, 1, 0, 0);
-
-        // Record part
-        List<DnsPacket.DnsRecord> qdRecordList =
-                packet.getRecordList(DnsPacket.QDSECTION);
-        assertEquals(qdRecordList.size(), 1);
-        assertRecordParses(qdRecordList.get(0), "www.google.com", 28, 1, 0, null);
-
-        List<DnsPacket.DnsRecord> anRecordList =
-                packet.getRecordList(DnsPacket.ANSECTION);
-        assertEquals(anRecordList.size(), 1);
-        assertRecordParses(anRecordList.get(0), "www.google.com", 28, 1, 0x37,
-                new byte[]{ 0x24, 0x04, 0x68, 0x00, 0x40, 0x05, 0x08, 0x0d,
-                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x04 });
-    }
-}
diff --git a/tests/net/java/android/net/NetworkUtilsTest.java b/tests/net/java/android/net/NetworkUtilsTest.java
index 7748288..3158cc8 100644
--- a/tests/net/java/android/net/NetworkUtilsTest.java
+++ b/tests/net/java/android/net/NetworkUtilsTest.java
@@ -16,10 +16,24 @@
 
 package android.net;
 
+import static android.system.OsConstants.AF_INET;
+import static android.system.OsConstants.AF_INET6;
+import static android.system.OsConstants.AF_UNIX;
+import static android.system.OsConstants.EPERM;
+import static android.system.OsConstants.SOCK_DGRAM;
+import static android.system.OsConstants.SOCK_STREAM;
+
 import static junit.framework.Assert.assertEquals;
 
+import static org.junit.Assert.fail;
+
+import android.system.ErrnoException;
+import android.system.Os;
+
 import androidx.test.runner.AndroidJUnit4;
 
+import libcore.io.IoUtils;
+
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -125,4 +139,50 @@
         assertEquals(BigInteger.valueOf(7l - 4 + 4 + 16 + 65536),
                 NetworkUtils.routedIPv6AddressCount(set));
     }
+
+    private static void expectSocketSuccess(String msg, int domain, int type) {
+        try {
+            IoUtils.closeQuietly(Os.socket(domain, type, 0));
+        } catch (ErrnoException e) {
+            fail(msg + e.getMessage());
+        }
+    }
+
+    private static void expectSocketPemissionError(String msg, int domain, int type) {
+        try {
+            IoUtils.closeQuietly(Os.socket(domain, type, 0));
+            fail(msg);
+        } catch (ErrnoException e) {
+            assertEquals(msg, e.errno, EPERM);
+        }
+    }
+
+    private static void expectHasNetworking() {
+        expectSocketSuccess("Creating a UNIX socket should not have thrown ErrnoException",
+                AF_UNIX, SOCK_STREAM);
+        expectSocketSuccess("Creating a AF_INET socket shouldn't have thrown ErrnoException",
+                AF_INET, SOCK_DGRAM);
+        expectSocketSuccess("Creating a AF_INET6 socket shouldn't have thrown ErrnoException",
+                AF_INET6, SOCK_DGRAM);
+    }
+
+    private static void expectNoNetworking() {
+        expectSocketSuccess("Creating a UNIX socket should not have thrown ErrnoException",
+                AF_UNIX, SOCK_STREAM);
+        expectSocketPemissionError(
+                "Creating a AF_INET socket should have thrown ErrnoException(EPERM)",
+                AF_INET, SOCK_DGRAM);
+        expectSocketPemissionError(
+                "Creating a AF_INET6 socket should have thrown ErrnoException(EPERM)",
+                AF_INET6, SOCK_DGRAM);
+    }
+
+    @Test
+    public void testSetAllowNetworkingForProcess() {
+        expectHasNetworking();
+        NetworkUtils.setAllowNetworkingForProcess(false);
+        expectNoNetworking();
+        NetworkUtils.setAllowNetworkingForProcess(true);
+        expectHasNetworking();
+    }
 }
diff --git a/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java b/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java
index 76e3e2f..5eea0e8 100644
--- a/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java
+++ b/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java
@@ -76,7 +76,6 @@
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 import org.mockito.invocation.InvocationOnMock;
@@ -88,7 +87,6 @@
 import java.util.HashSet;
 import java.util.Set;
 
-
 @RunWith(AndroidJUnit4.class)
 @SmallTest
 public class PermissionMonitorTest {
@@ -117,7 +115,6 @@
     @Mock private PackageManagerInternal mMockPmi;
     @Mock private UserManager mUserManager;
 
-    private PackageManagerInternal.PackageListObserver mObserver;
     private PermissionMonitor mPermissionMonitor;
 
     @Before
@@ -139,11 +136,7 @@
                   /* observer */ null));
         when(mPackageManager.getInstalledPackages(anyInt())).thenReturn(/* empty app list */ null);
         mPermissionMonitor.startMonitoring();
-
-        final ArgumentCaptor<PackageManagerInternal.PackageListObserver> observerCaptor =
-                ArgumentCaptor.forClass(PackageManagerInternal.PackageListObserver.class);
-        verify(mMockPmi).getPackageList(observerCaptor.capture());
-        mObserver = observerCaptor.getValue();
+        verify(mMockPmi).getPackageList(mPermissionMonitor);
     }
 
     private boolean hasRestrictedNetworkPermission(String partition, int targetSdkVersion, int uid,
@@ -450,13 +443,13 @@
                 new int[]{MOCK_UID1});
 
         // Remove MOCK_UID1, expect no permission left for all user.
-        mPermissionMonitor.onPackageRemoved(MOCK_UID1);
-        removePackageForUsers(new int[]{MOCK_USER1, MOCK_USER2}, MOCK_UID1);
+        mPermissionMonitor.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1);
+        removePackageForUsers(new int[]{MOCK_USER1, MOCK_USER2}, MOCK_PACKAGE1, MOCK_UID1);
         mNetdMonitor.expectNoPermission(new int[]{MOCK_USER1, MOCK_USER2}, new int[]{MOCK_UID1});
 
         // Remove SYSTEM_PACKAGE1, expect permission downgrade.
         when(mPackageManager.getPackagesForUid(anyInt())).thenReturn(new String[]{SYSTEM_PACKAGE2});
-        removePackageForUsers(new int[]{MOCK_USER1, MOCK_USER2}, SYSTEM_UID);
+        removePackageForUsers(new int[]{MOCK_USER1, MOCK_USER2}, SYSTEM_PACKAGE1, SYSTEM_UID);
         mNetdMonitor.expectPermission(NETWORK, new int[]{MOCK_USER1, MOCK_USER2},
                 new int[]{SYSTEM_UID});
 
@@ -465,7 +458,7 @@
 
         // Remove all packages, expect no permission left.
         when(mPackageManager.getPackagesForUid(anyInt())).thenReturn(new String[]{});
-        removePackageForUsers(new int[]{MOCK_USER2}, SYSTEM_UID);
+        removePackageForUsers(new int[]{MOCK_USER2}, SYSTEM_PACKAGE2, SYSTEM_UID);
         mNetdMonitor.expectNoPermission(new int[]{MOCK_USER1, MOCK_USER2},
                 new int[]{SYSTEM_UID, MOCK_UID1});
 
@@ -501,7 +494,8 @@
         reset(mNetdService);
 
         // When MOCK_UID1 package is uninstalled and reinstalled, expect Netd to be updated
-        mPermissionMonitor.onPackageRemoved(UserHandle.getUid(MOCK_USER1, MOCK_UID1));
+        mPermissionMonitor.onPackageRemoved(
+                MOCK_PACKAGE1, UserHandle.getUid(MOCK_USER1, MOCK_UID1));
         verify(mNetdService).firewallRemoveUidInterfaceRules(aryEq(new int[] {MOCK_UID1}));
         mPermissionMonitor.onPackageAdded(MOCK_PACKAGE1, UserHandle.getUid(MOCK_USER1, MOCK_UID1));
         verify(mNetdService).firewallAddUidInterfaceRules(eq("tun0"),
@@ -545,7 +539,8 @@
                 aryEq(new int[] {MOCK_UID1}));
 
         // Removed package should have its uid rules removed
-        mPermissionMonitor.onPackageRemoved(UserHandle.getUid(MOCK_USER1, MOCK_UID1));
+        mPermissionMonitor.onPackageRemoved(
+                MOCK_PACKAGE1, UserHandle.getUid(MOCK_USER1, MOCK_UID1));
         verify(mNetdService).firewallRemoveUidInterfaceRules(aryEq(new int[] {MOCK_UID1}));
     }
 
@@ -559,9 +554,9 @@
         }
     }
 
-    private void removePackageForUsers(int[] users, int uid) {
+    private void removePackageForUsers(int[] users, String packageName, int uid) {
         for (final int user : users) {
-            mPermissionMonitor.onPackageRemoved(UserHandle.getUid(user, uid));
+            mPermissionMonitor.onPackageRemoved(packageName, UserHandle.getUid(user, uid));
         }
     }
 
@@ -647,7 +642,7 @@
     private PackageInfo addPackage(String packageName, int uid, String[] permissions)
             throws Exception {
         PackageInfo packageInfo = setPackagePermissions(packageName, uid, permissions);
-        mObserver.onPackageAdded(packageName, uid);
+        mPermissionMonitor.onPackageAdded(packageName, uid);
         return packageInfo;
     }
 
@@ -678,7 +673,7 @@
         when(mPackageManager.getPackageInfo(eq(MOCK_PACKAGE2), anyInt())).thenReturn(packageInfo2);
         when(mPackageManager.getPackagesForUid(MOCK_UID1))
               .thenReturn(new String[]{MOCK_PACKAGE1, MOCK_PACKAGE2});
-        mObserver.onPackageAdded(MOCK_PACKAGE2, MOCK_UID1);
+        mPermissionMonitor.onPackageAdded(MOCK_PACKAGE2, MOCK_UID1);
         mNetdServiceMonitor.expectPermission(INetd.PERMISSION_INTERNET
                 | INetd.PERMISSION_UPDATE_DEVICE_STATS, new int[]{MOCK_UID1});
     }
@@ -692,7 +687,7 @@
                 | INetd.PERMISSION_UPDATE_DEVICE_STATS, new int[]{MOCK_UID1});
 
         when(mPackageManager.getPackagesForUid(MOCK_UID1)).thenReturn(new String[]{});
-        mObserver.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1);
+        mPermissionMonitor.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1);
         mNetdServiceMonitor.expectPermission(INetd.PERMISSION_UNINSTALLED, new int[]{MOCK_UID1});
     }
 
@@ -705,7 +700,7 @@
                 | INetd.PERMISSION_UPDATE_DEVICE_STATS, new int[]{MOCK_UID1});
 
         when(mPackageManager.getPackagesForUid(MOCK_UID1)).thenReturn(new String[]{});
-        mObserver.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1);
+        mPermissionMonitor.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1);
         mNetdServiceMonitor.expectPermission(INetd.PERMISSION_UNINSTALLED, new int[]{MOCK_UID1});
 
         addPackage(MOCK_PACKAGE1, MOCK_UID1, new String[] {INTERNET});
@@ -719,10 +714,7 @@
         addPackage(MOCK_PACKAGE1, MOCK_UID1, new String[] {});
         mNetdServiceMonitor.expectPermission(INetd.PERMISSION_NONE, new int[]{MOCK_UID1});
 
-        // When updating a package, the broadcast receiver gets two broadcasts (a remove and then an
-        // add), but the observer sees only one callback (an update).
-        setPackagePermissions(MOCK_PACKAGE1, MOCK_UID1, new String[] {INTERNET});
-        mObserver.onPackageChanged(MOCK_PACKAGE1, MOCK_UID1);
+        addPackage(MOCK_PACKAGE1, MOCK_UID1, new String[] {INTERNET});
         mNetdServiceMonitor.expectPermission(INetd.PERMISSION_INTERNET, new int[]{MOCK_UID1});
     }
 
@@ -740,7 +732,7 @@
         when(mPackageManager.getPackagesForUid(MOCK_UID1)).thenReturn(new String[]{
                 MOCK_PACKAGE2});
 
-        mObserver.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1);
+        mPermissionMonitor.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1);
         mNetdServiceMonitor.expectPermission(INetd.PERMISSION_INTERNET, new int[]{MOCK_UID1});
     }
 
diff --git a/tools/aapt2/cmd/Link.cpp b/tools/aapt2/cmd/Link.cpp
index 7afb000..85414fb 100644
--- a/tools/aapt2/cmd/Link.cpp
+++ b/tools/aapt2/cmd/Link.cpp
@@ -1252,7 +1252,8 @@
       return false;
     }
 
-    ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
+    ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true,
+                                   false /* strip_api_annotations */, &fout);
     fout.Flush();
 
     if (fout.HadError()) {
diff --git a/tools/aapt2/java/AnnotationProcessor.cpp b/tools/aapt2/java/AnnotationProcessor.cpp
index a4610b2..bb667d6 100644
--- a/tools/aapt2/java/AnnotationProcessor.cpp
+++ b/tools/aapt2/java/AnnotationProcessor.cpp
@@ -110,7 +110,7 @@
   }
 }
 
-void AnnotationProcessor::Print(Printer* printer) const {
+void AnnotationProcessor::Print(Printer* printer, bool strip_api_annotations) const {
   if (has_comments_) {
     std::string result = comment_.str();
     for (const StringPiece& line : util::Tokenize(result, '\n')) {
@@ -123,6 +123,9 @@
     printer->Println("@Deprecated");
   }
 
+  if (strip_api_annotations) {
+    return;
+  }
   for (const AnnotationRule& rule : sAnnotationRules) {
     if (annotation_bit_mask_ & rule.bit_mask) {
       printer->Println(rule.annotation);
diff --git a/tools/aapt2/java/AnnotationProcessor.h b/tools/aapt2/java/AnnotationProcessor.h
index ae7bdb0..6d768be 100644
--- a/tools/aapt2/java/AnnotationProcessor.h
+++ b/tools/aapt2/java/AnnotationProcessor.h
@@ -64,7 +64,7 @@
   void AppendNewLine();
 
   // Writes the comments and annotations to the Printer.
-  void Print(text::Printer* printer) const;
+  void Print(text::Printer* printer, bool strip_api_annotations = false) const;
 
  private:
   std::stringstream comment_;
diff --git a/tools/aapt2/java/AnnotationProcessor_test.cpp b/tools/aapt2/java/AnnotationProcessor_test.cpp
index 69f49c8..c4c8ff9 100644
--- a/tools/aapt2/java/AnnotationProcessor_test.cpp
+++ b/tools/aapt2/java/AnnotationProcessor_test.cpp
@@ -76,6 +76,21 @@
   EXPECT_THAT(annotations, HasSubstr("This is a test API"));
 }
 
+TEST(AnnotationProcessorTest, NotEmitSystemApiAnnotation) {
+  AnnotationProcessor processor;
+  processor.AppendComment("@SystemApi This is a system API");
+
+  std::string annotations;
+  StringOutputStream out(&annotations);
+  Printer printer(&out);
+  processor.Print(&printer, true /* strip_api_annotations */);
+  out.Flush();
+
+  EXPECT_THAT(annotations, Not(HasSubstr("@android.annotation.SystemApi")));
+  EXPECT_THAT(annotations, Not(HasSubstr("@SystemApi")));
+  EXPECT_THAT(annotations, HasSubstr("This is a system API"));
+}
+
 TEST(AnnotationProcessor, ExtractsFirstSentence) {
   EXPECT_THAT(AnnotationProcessor::ExtractFirstSentence("This is the only sentence"),
               Eq("This is the only sentence"));
diff --git a/tools/aapt2/java/ClassDefinition.cpp b/tools/aapt2/java/ClassDefinition.cpp
index f5f5b05..3163497 100644
--- a/tools/aapt2/java/ClassDefinition.cpp
+++ b/tools/aapt2/java/ClassDefinition.cpp
@@ -23,15 +23,15 @@
 
 namespace aapt {
 
-void ClassMember::Print(bool /*final*/, Printer* printer) const {
-  processor_.Print(printer);
+void ClassMember::Print(bool /*final*/, Printer* printer, bool strip_api_annotations) const {
+  processor_.Print(printer, strip_api_annotations);
 }
 
 void MethodDefinition::AppendStatement(const StringPiece& statement) {
   statements_.push_back(statement.to_string());
 }
 
-void MethodDefinition::Print(bool final, Printer* printer) const {
+void MethodDefinition::Print(bool final, Printer* printer, bool) const {
   printer->Print(signature_).Println(" {");
   printer->Indent();
   for (const auto& statement : statements_) {
@@ -74,12 +74,12 @@
   return true;
 }
 
-void ClassDefinition::Print(bool final, Printer* printer) const {
+void ClassDefinition::Print(bool final, Printer* printer, bool strip_api_annotations) const {
   if (empty() && !create_if_empty_) {
     return;
   }
 
-  ClassMember::Print(final, printer);
+  ClassMember::Print(final,  printer, strip_api_annotations);
 
   printer->Print("public ");
   if (qualifier_ == ClassQualifier::kStatic) {
@@ -93,7 +93,7 @@
     // and takes precedence over a previous member with the same name. The overridden member is
     // set to nullptr.
     if (member != nullptr) {
-      member->Print(final, printer);
+      member->Print(final, printer, strip_api_annotations);
       printer->Println();
     }
   }
@@ -111,11 +111,11 @@
     " */\n\n";
 
 void ClassDefinition::WriteJavaFile(const ClassDefinition* def, const StringPiece& package,
-                                    bool final, io::OutputStream* out) {
+                                    bool final, bool strip_api_annotations, io::OutputStream* out) {
   Printer printer(out);
   printer.Print(sWarningHeader).Print("package ").Print(package).Println(";");
   printer.Println();
-  def->Print(final, &printer);
+  def->Print(final, &printer, strip_api_annotations);
 }
 
 }  // namespace aapt
diff --git a/tools/aapt2/java/ClassDefinition.h b/tools/aapt2/java/ClassDefinition.h
index fb11266..1e4b681 100644
--- a/tools/aapt2/java/ClassDefinition.h
+++ b/tools/aapt2/java/ClassDefinition.h
@@ -50,7 +50,7 @@
   // Writes the class member to the Printer. Subclasses should derive this method
   // to write their own data. Call this base method from the subclass to write out
   // this member's comments/annotations.
-  virtual void Print(bool final, text::Printer* printer) const;
+  virtual void Print(bool final, text::Printer* printer, bool strip_api_annotations = false) const;
 
  private:
   AnnotationProcessor processor_;
@@ -70,10 +70,11 @@
     return name_;
   }
 
-  void Print(bool final, text::Printer* printer) const override {
+  void Print(bool final, text::Printer* printer, bool strip_api_annotations = false)
+      const override {
     using std::to_string;
 
-    ClassMember::Print(final, printer);
+    ClassMember::Print(final, printer, strip_api_annotations);
 
     printer->Print("public static ");
     if (final) {
@@ -104,8 +105,9 @@
     return name_;
   }
 
-  void Print(bool final, text::Printer* printer) const override {
-    ClassMember::Print(final, printer);
+  void Print(bool final, text::Printer* printer, bool strip_api_annotations = false)
+      const override {
+    ClassMember::Print(final, printer, strip_api_annotations);
 
     printer->Print("public static ");
     if (final) {
@@ -142,8 +144,9 @@
     return name_;
   }
 
-  void Print(bool final, text::Printer* printer) const override {
-    ClassMember::Print(final, printer);
+  void Print(bool final, text::Printer* printer, bool strip_api_annotations = false)
+      const override {
+    ClassMember::Print(final, printer, strip_api_annotations);
 
     printer->Print("public static final int[] ").Print(name_).Print("={");
     printer->Indent();
@@ -195,7 +198,7 @@
     return false;
   }
 
-  void Print(bool final, text::Printer* printer) const override;
+  void Print(bool final, text::Printer* printer, bool strip_api_annotations = false) const override;
 
  private:
   DISALLOW_COPY_AND_ASSIGN(MethodDefinition);
@@ -209,7 +212,7 @@
 class ClassDefinition : public ClassMember {
  public:
   static void WriteJavaFile(const ClassDefinition* def, const android::StringPiece& package,
-                            bool final, io::OutputStream* out);
+                            bool final, bool strip_api_annotations, io::OutputStream* out);
 
   ClassDefinition(const android::StringPiece& name, ClassQualifier qualifier, bool createIfEmpty)
       : name_(name.to_string()), qualifier_(qualifier), create_if_empty_(createIfEmpty) {}
@@ -227,7 +230,7 @@
     return name_;
   }
 
-  void Print(bool final, text::Printer* printer) const override;
+  void Print(bool final, text::Printer* printer, bool strip_api_annotations = false) const override;
 
  private:
   DISALLOW_COPY_AND_ASSIGN(ClassDefinition);
diff --git a/tools/aapt2/java/JavaClassGenerator.cpp b/tools/aapt2/java/JavaClassGenerator.cpp
index 31d205e..9788f64 100644
--- a/tools/aapt2/java/JavaClassGenerator.cpp
+++ b/tools/aapt2/java/JavaClassGenerator.cpp
@@ -601,6 +601,8 @@
     }
   }
 
+  const bool is_public = (options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic);
+
   for (const auto& package : table_->packages) {
     for (const auto& type : package->types) {
       if (type->type == ResourceType::kAttrPrivate) {
@@ -609,8 +611,7 @@
       }
 
       // Stay consistent with AAPT and generate an empty type class if the R class is public.
-      const bool force_creation_if_empty =
-          (options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic);
+      const bool force_creation_if_empty = is_public;
 
       std::unique_ptr<ClassDefinition> class_def;
       if (out != nullptr) {
@@ -634,8 +635,7 @@
         }
       }
 
-      if (out != nullptr && type->type == ResourceType::kStyleable &&
-          options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic) {
+      if (out != nullptr && type->type == ResourceType::kStyleable && is_public) {
         // When generating a public R class, we don't want Styleable to be part
         // of the API. It is only emitted for documentation purposes.
         class_def->GetCommentBuilder()->AppendComment("@doconly");
@@ -654,7 +654,7 @@
 
   if (out != nullptr) {
     AppendJavaDocAnnotations(options_.javadoc_annotations, r_class.GetCommentBuilder());
-    ClassDefinition::WriteJavaFile(&r_class, out_package_name, options_.use_final, out);
+    ClassDefinition::WriteJavaFile(&r_class, out_package_name, options_.use_final, !is_public, out);
   }
   return true;
 }
diff --git a/tools/aapt2/java/ManifestClassGenerator_test.cpp b/tools/aapt2/java/ManifestClassGenerator_test.cpp
index ab7f9a1..3858fc7 100644
--- a/tools/aapt2/java/ManifestClassGenerator_test.cpp
+++ b/tools/aapt2/java/ManifestClassGenerator_test.cpp
@@ -26,6 +26,7 @@
 namespace aapt {
 
 static ::testing::AssertionResult GetManifestClassText(IAaptContext* context, xml::XmlResource* res,
+                                                       bool strip_api_annotations,
                                                        std::string* out_str);
 
 TEST(ManifestClassGeneratorTest, NameIsProperlyGeneratedFromSymbol) {
@@ -39,7 +40,8 @@
       </manifest>)");
 
   std::string actual;
-  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(), &actual));
+  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(),
+                                   false /* strip_api_annotations */, &actual));
 
   ASSERT_THAT(actual, HasSubstr("public static final class permission {"));
   ASSERT_THAT(actual, HasSubstr("public static final class permission_group {"));
@@ -91,7 +93,8 @@
       </manifest>)");
 
   std::string actual;
-  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(), &actual));
+  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(),
+                                   false /* strip_api_annotations */, &actual));
 
   const char* expected_access_internet = R"(    /**
      * Required to access the internet.
@@ -123,6 +126,55 @@
   EXPECT_THAT(actual, HasSubstr(expected_test));
 }
 
+TEST(ManifestClassGeneratorTest, CommentsAndAnnotationsArePresentButNoApiAnnotations) {
+  std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
+  std::unique_ptr<xml::XmlResource> manifest = test::BuildXmlDom(R"(
+      <manifest xmlns:android="http://schemas.android.com/apk/res/android">
+        <!-- Required to access the internet.
+             Added in API 1. -->
+        <permission android:name="android.permission.ACCESS_INTERNET" />
+        <!-- @deprecated This permission is for playing outside. -->
+        <permission android:name="android.permission.PLAY_OUTSIDE" />
+        <!-- This is a private permission for system only!
+             @hide
+             @SystemApi -->
+        <permission android:name="android.permission.SECRET" />
+        <!-- @TestApi This is a test only permission. -->
+        <permission android:name="android.permission.TEST_ONLY" />
+      </manifest>)");
+
+  std::string actual;
+  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(),
+                                   true /* strip_api_annotations */, &actual));
+
+  const char* expected_access_internet = R"(    /**
+     * Required to access the internet.
+     * Added in API 1.
+     */
+    public static final String ACCESS_INTERNET="android.permission.ACCESS_INTERNET";)";
+  EXPECT_THAT(actual, HasSubstr(expected_access_internet));
+
+  const char* expected_play_outside = R"(    /**
+     * @deprecated This permission is for playing outside.
+     */
+    @Deprecated
+    public static final String PLAY_OUTSIDE="android.permission.PLAY_OUTSIDE";)";
+  EXPECT_THAT(actual, HasSubstr(expected_play_outside));
+
+  const char* expected_secret = R"(    /**
+     * This is a private permission for system only!
+     * @hide
+     */
+    public static final String SECRET="android.permission.SECRET";)";
+  EXPECT_THAT(actual, HasSubstr(expected_secret));
+
+  const char* expected_test = R"(    /**
+     * This is a test only permission.
+     */
+    public static final String TEST_ONLY="android.permission.TEST_ONLY";)";
+  EXPECT_THAT(actual, HasSubstr(expected_test));
+}
+
 // This is bad but part of public API behaviour so we need to preserve it.
 TEST(ManifestClassGeneratorTest, LastSeenPermissionWithSameLeafNameTakesPrecedence) {
   std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
@@ -135,7 +187,8 @@
       </manifest>)");
 
   std::string actual;
-  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(), &actual));
+  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(),
+                                   false  /* strip_api_annotations */, &actual));
   EXPECT_THAT(actual, HasSubstr("ACCESS_INTERNET=\"com.android.aapt.test.ACCESS_INTERNET\";"));
   EXPECT_THAT(actual, Not(HasSubstr("ACCESS_INTERNET=\"android.permission.ACCESS_INTERNET\";")));
   EXPECT_THAT(actual, Not(HasSubstr("ACCESS_INTERNET=\"com.android.sample.ACCESS_INTERNET\";")));
@@ -149,11 +202,13 @@
         </manifest>)");
 
   std::string actual;
-  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(), &actual));
+  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(),
+                                   false  /* strip_api_annotations */, &actual));
   EXPECT_THAT(actual, HasSubstr("access_internet=\"android.permission.access-internet\";"));
 }
 
 static ::testing::AssertionResult GetManifestClassText(IAaptContext* context, xml::XmlResource* res,
+                                                       bool strip_api_annotations,
                                                        std::string* out_str) {
   std::unique_ptr<ClassDefinition> manifest_class =
       GenerateManifestClass(context->GetDiagnostics(), res);
@@ -162,7 +217,7 @@
   }
 
   StringOutputStream out(out_str);
-  manifest_class->WriteJavaFile(manifest_class.get(), "android", true, &out);
+  manifest_class->WriteJavaFile(manifest_class.get(), "android", true, strip_api_annotations, &out);
   out.Flush();
   return ::testing::AssertionSuccess();
 }