Merge "RescueParty: Add a DeviceConfig killswitch" into rvc-dev
diff --git a/api/current.txt b/api/current.txt
index 86fb857..7256461 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -43016,12 +43016,12 @@
   }
 
   public static final class Dataset.Builder {
-    ctor public Dataset.Builder(@NonNull android.widget.RemoteViews, @NonNull android.service.autofill.InlinePresentation);
     ctor public Dataset.Builder(@NonNull android.widget.RemoteViews);
     ctor public Dataset.Builder();
     method @NonNull public android.service.autofill.Dataset build();
     method @NonNull public android.service.autofill.Dataset.Builder setAuthentication(@Nullable android.content.IntentSender);
     method @NonNull public android.service.autofill.Dataset.Builder setId(@Nullable String);
+    method @NonNull public android.service.autofill.Dataset.Builder setInlinePresentation(@NonNull android.service.autofill.InlinePresentation);
     method @NonNull public android.service.autofill.Dataset.Builder setValue(@NonNull android.view.autofill.AutofillId, @Nullable android.view.autofill.AutofillValue);
     method @NonNull public android.service.autofill.Dataset.Builder setValue(@NonNull android.view.autofill.AutofillId, @Nullable android.view.autofill.AutofillValue, @NonNull android.widget.RemoteViews);
     method @NonNull public android.service.autofill.Dataset.Builder setValue(@NonNull android.view.autofill.AutofillId, @Nullable android.view.autofill.AutofillValue, @Nullable java.util.regex.Pattern);
diff --git a/api/system-current.txt b/api/system-current.txt
index 0fb6919..51f3425 100755
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -2216,7 +2216,7 @@
     field public static final String FEATURE_INCREMENTAL_DELIVERY = "android.software.incremental_delivery";
     field public static final String FEATURE_REBOOT_ESCROW = "android.hardware.reboot_escrow";
     field public static final String FEATURE_TELEPHONY_CARRIERLOCK = "android.hardware.telephony.carrierlock";
-    field public static final int FLAGS_PERMISSION_RESERVED_PERMISSIONCONTROLLER = -268435456; // 0xf0000000
+    field public static final int FLAGS_PERMISSION_RESERVED_PERMISSION_CONTROLLER = -268435456; // 0xf0000000
     field public static final int FLAG_PERMISSION_APPLY_RESTRICTION = 16384; // 0x4000
     field public static final int FLAG_PERMISSION_AUTO_REVOKED = 131072; // 0x20000
     field public static final int FLAG_PERMISSION_GRANTED_BY_DEFAULT = 32; // 0x20
@@ -9798,7 +9798,7 @@
 
   public static final class Dataset.Builder {
     ctor public Dataset.Builder(@NonNull android.service.autofill.InlinePresentation);
-    method @NonNull public android.service.autofill.Dataset.Builder setInlinePresentation(@NonNull android.view.autofill.AutofillId, @Nullable android.view.autofill.AutofillValue, @Nullable java.util.regex.Pattern, @NonNull android.service.autofill.InlinePresentation);
+    method @NonNull public android.service.autofill.Dataset.Builder setFieldInlinePresentation(@NonNull android.view.autofill.AutofillId, @Nullable android.view.autofill.AutofillValue, @Nullable java.util.regex.Pattern, @NonNull android.service.autofill.InlinePresentation);
   }
 
   public abstract class InlineSuggestionRenderService extends android.app.Service {
diff --git a/api/test-current.txt b/api/test-current.txt
index 9045646..730a2a2 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -3134,7 +3134,7 @@
 
   public static final class Dataset.Builder {
     ctor public Dataset.Builder(@NonNull android.service.autofill.InlinePresentation);
-    method @NonNull public android.service.autofill.Dataset.Builder setInlinePresentation(@NonNull android.view.autofill.AutofillId, @Nullable android.view.autofill.AutofillValue, @Nullable java.util.regex.Pattern, @NonNull android.service.autofill.InlinePresentation);
+    method @NonNull public android.service.autofill.Dataset.Builder setFieldInlinePresentation(@NonNull android.view.autofill.AutofillId, @Nullable android.view.autofill.AutofillValue, @Nullable java.util.regex.Pattern, @NonNull android.service.autofill.InlinePresentation);
   }
 
   public final class DateTransformation extends android.service.autofill.InternalTransformation implements android.os.Parcelable android.service.autofill.Transformation {
@@ -4970,7 +4970,7 @@
     method public void resetRtlProperties();
     method public boolean restoreFocusInCluster(int);
     method public boolean restoreFocusNotInCluster();
-    method public void setAutofilled(boolean);
+    method public void setAutofilled(boolean, boolean);
     method public final void setFocusedInCluster();
     method public void setIsRootNamespace(boolean);
     method public final void setShowingLayoutBounds(boolean);
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index 8895a02..347648a 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -8804,10 +8804,11 @@
      * <p>
      * The following settings used to be supported, but can be controlled in other ways:
      * <ul>
-     * <li>{@link android.provider.Settings.Global#AUTO_TIME} : Use {@link #setAutoTime} and
+     * <li>{@link android.provider.Settings.Global#AUTO_TIME} : Use {@link #setAutoTimeEnabled} and
      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} instead.</li>
-     * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE} : Use {@link #setAutoTimeZone}
-     * and {@link UserManager#DISALLOW_CONFIG_DATE_TIME} instead.</li>
+     * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE} : Use
+     * {@link #setAutoTimeZoneEnabled} and {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
+     * instead.</li>
      * <li>{@link android.provider.Settings.Global#DATA_ROAMING} : Use
      * {@link UserManager#DISALLOW_DATA_ROAMING} instead.</li>
      * </ul>
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 7600a08..b0964fa 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -3411,12 +3411,13 @@
     public static final int FLAG_PERMISSION_AUTO_REVOKED = 1 << 17;
 
     /**
-     * Permission flags: Reserved for use by the permission controller.
-     *
+     * Permission flags: Reserved for use by the permission controller. The platform and any
+     * packages besides the permission controller should not assume any definition about these
+     * flags.
      * @hide
      */
     @SystemApi
-    public static final int FLAGS_PERMISSION_RESERVED_PERMISSIONCONTROLLER = 1 << 28 | 1 << 29
+    public static final int FLAGS_PERMISSION_RESERVED_PERMISSION_CONTROLLER = 1 << 28 | 1 << 29
             | 1 << 30 | 1 << 31;
 
     /**
diff --git a/core/java/android/service/autofill/Dataset.java b/core/java/android/service/autofill/Dataset.java
index 886b433..08aa534 100644
--- a/core/java/android/service/autofill/Dataset.java
+++ b/core/java/android/service/autofill/Dataset.java
@@ -232,22 +232,6 @@
          * Creates a new builder.
          *
          * @param presentation The presentation used to visualize this dataset.
-         * @param inlinePresentation The {@link InlinePresentation} used to visualize this dataset
-         *              as inline suggestions. If the dataset supports inline suggestions,
-         *              this should not be null.
-         */
-        public Builder(@NonNull RemoteViews presentation,
-                @NonNull InlinePresentation inlinePresentation) {
-            Preconditions.checkNotNull(presentation, "presentation must be non-null");
-            Preconditions.checkNotNull(inlinePresentation, "inlinePresentation must be non-null");
-            mPresentation = presentation;
-            mInlinePresentation = inlinePresentation;
-        }
-
-        /**
-         * Creates a new builder.
-         *
-         * @param presentation The presentation used to visualize this dataset.
          */
         public Builder(@NonNull RemoteViews presentation) {
             Preconditions.checkNotNull(presentation, "presentation must be non-null");
@@ -282,6 +266,22 @@
         }
 
         /**
+         * Sets the {@link InlinePresentation} used to visualize this dataset as inline suggestions.
+         * If the dataset supports inline suggestions this should not be null.
+         *
+         * @throws IllegalStateException if {@link #build()} was already called.
+         *
+         * @return this builder.
+         */
+        public @NonNull Builder setInlinePresentation(
+                @NonNull InlinePresentation inlinePresentation) {
+            throwIfDestroyed();
+            Preconditions.checkNotNull(inlinePresentation, "inlinePresentation must be non-null");
+            mInlinePresentation = inlinePresentation;
+            return this;
+        }
+
+        /**
          * Triggers a custom UI before before autofilling the screen with the contents of this
          * dataset.
          *
@@ -600,7 +600,7 @@
          */
         @SystemApi
         @TestApi
-        public @NonNull Builder setInlinePresentation(@NonNull AutofillId id,
+        public @NonNull Builder setFieldInlinePresentation(@NonNull AutofillId id,
                 @Nullable AutofillValue value, @Nullable Pattern filter,
                 @NonNull InlinePresentation inlinePresentation) {
             throwIfDestroyed();
@@ -700,7 +700,7 @@
             final Builder builder = presentation != null
                     ? inlinePresentation == null
                             ? new Builder(presentation)
-                            : new Builder(presentation, inlinePresentation)
+                            : new Builder(presentation).setInlinePresentation(inlinePresentation)
                     : inlinePresentation == null
                             ? new Builder()
                             : new Builder(inlinePresentation);
diff --git a/core/java/android/service/autofill/IInlineSuggestionUiCallback.aidl b/core/java/android/service/autofill/IInlineSuggestionUiCallback.aidl
index 1011651..1bcc76b 100644
--- a/core/java/android/service/autofill/IInlineSuggestionUiCallback.aidl
+++ b/core/java/android/service/autofill/IInlineSuggestionUiCallback.aidl
@@ -25,7 +25,8 @@
  * @hide
  */
 oneway interface IInlineSuggestionUiCallback {
-    void onAutofill();
+    void onClick();
+    void onLongClick();
     void onContent(in SurfaceControlViewHost.SurfacePackage surface);
     void onError();
     void onTransferTouchFocusToImeWindow(in IBinder sourceInputToken, int displayId);
diff --git a/core/java/android/service/autofill/InlineSuggestionRenderService.java b/core/java/android/service/autofill/InlineSuggestionRenderService.java
index ee15283..b6cc62d 100644
--- a/core/java/android/service/autofill/InlineSuggestionRenderService.java
+++ b/core/java/android/service/autofill/InlineSuggestionRenderService.java
@@ -97,12 +97,21 @@
             host.addView(suggestionRoot, lp);
             suggestionRoot.setOnClickListener((v) -> {
                 try {
-                    callback.onAutofill();
+                    callback.onClick();
                 } catch (RemoteException e) {
-                    Log.w(TAG, "RemoteException calling onAutofill()");
+                    Log.w(TAG, "RemoteException calling onClick()");
                 }
             });
 
+            suggestionRoot.setOnLongClickListener((v) -> {
+                try {
+                    callback.onLongClick();
+                } catch (RemoteException e) {
+                    Log.w(TAG, "RemoteException calling onLongClick()");
+                }
+                return true;
+            });
+
             sendResult(callback, host.getSurfacePackage());
         } finally {
             updateDisplay(Display.DEFAULT_DISPLAY);
diff --git a/core/java/android/service/autofill/augmented/AugmentedAutofillService.java b/core/java/android/service/autofill/augmented/AugmentedAutofillService.java
index ed27dd5..5b08ae2 100644
--- a/core/java/android/service/autofill/augmented/AugmentedAutofillService.java
+++ b/core/java/android/service/autofill/augmented/AugmentedAutofillService.java
@@ -488,7 +488,8 @@
                 ids.add(pair.first);
                 values.add(pair.second);
             }
-            mClient.autofill(mSessionId, ids, values);
+            final boolean hideHighlight = size == 1 && ids.get(0).equals(mFocusedId);
+            mClient.autofill(mSessionId, ids, values, hideHighlight);
         }
 
         public void setFillWindow(@NonNull FillWindow fillWindow) {
diff --git a/core/java/android/util/apk/SourceStampVerifier.java b/core/java/android/util/apk/SourceStampVerifier.java
index 759c864..70e4a51 100644
--- a/core/java/android/util/apk/SourceStampVerifier.java
+++ b/core/java/android/util/apk/SourceStampVerifier.java
@@ -82,25 +82,34 @@
     public static SourceStampVerificationResult verify(String apkFile) {
         try (RandomAccessFile apk = new RandomAccessFile(apkFile, "r")) {
             return verify(apk);
-        } catch (Exception e) {
-            // Any exception in the SourceStamp verification returns a non-verified SourceStamp
-            // outcome without affecting the outcome of any of the other signature schemes.
-            return SourceStampVerificationResult.notVerified();
+        } catch (IOException e) {
+            // Any exception in reading the APK returns a non-present SourceStamp outcome
+            // without affecting the outcome of any of the other signature schemes.
+            return SourceStampVerificationResult.notPresent();
         }
     }
 
-    private static SourceStampVerificationResult verify(RandomAccessFile apk)
-            throws IOException, SignatureNotFoundException {
-        byte[] sourceStampCertificateDigest = getSourceStampCertificateDigest(apk);
-        if (sourceStampCertificateDigest == null) {
-            // SourceStamp certificate hash file not found, which means that there is not
-            // SourceStamp present.
+    private static SourceStampVerificationResult verify(RandomAccessFile apk) {
+        byte[] sourceStampCertificateDigest;
+        try {
+            sourceStampCertificateDigest = getSourceStampCertificateDigest(apk);
+            if (sourceStampCertificateDigest == null) {
+                // SourceStamp certificate hash file not found, which means that there is not
+                // SourceStamp present.
+                return SourceStampVerificationResult.notPresent();
+            }
+        } catch (IOException e) {
             return SourceStampVerificationResult.notPresent();
         }
-        SignatureInfo signatureInfo =
-                ApkSigningBlockUtils.findSignature(apk, SOURCE_STAMP_BLOCK_ID);
-        Map<Integer, byte[]> apkContentDigests = getApkContentDigests(apk);
-        return verify(signatureInfo, apkContentDigests, sourceStampCertificateDigest);
+
+        try {
+            SignatureInfo signatureInfo =
+                    ApkSigningBlockUtils.findSignature(apk, SOURCE_STAMP_BLOCK_ID);
+            Map<Integer, byte[]> apkContentDigests = getApkContentDigests(apk);
+            return verify(signatureInfo, apkContentDigests, sourceStampCertificateDigest);
+        } catch (IOException | SignatureNotFoundException e) {
+            return SourceStampVerificationResult.notVerified();
+        }
     }
 
     private static SourceStampVerificationResult verify(
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 879f284..e665f06 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -3318,7 +3318,7 @@
      * Flag indicating that the view is autofilled
      *
      * @see #isAutofilled()
-     * @see #setAutofilled(boolean)
+     * @see #setAutofilled(boolean, boolean)
      */
     private static final int PFLAG3_IS_AUTOFILLED = 0x10000;
 
@@ -3428,6 +3428,7 @@
      *                         1        PFLAG4_CONTENT_CAPTURE_IMPORTANCE_CACHED_VALUE
      *                         11       PFLAG4_CONTENT_CAPTURE_IMPORTANCE_MASK
      *                        1         PFLAG4_FRAMEWORK_OPTIONAL_FITS_SYSTEM_WINDOWS
+     *                       1          PFLAG4_AUTOFILL_HIDE_HIGHLIGHT
      * |-------|-------|-------|-------|
      */
 
@@ -3470,6 +3471,11 @@
      */
     static final int PFLAG4_FRAMEWORK_OPTIONAL_FITS_SYSTEM_WINDOWS = 0x000000100;
 
+    /**
+     * Flag indicating the field should not have yellow highlight when autofilled.
+     */
+    private static final int PFLAG4_AUTOFILL_HIDE_HIGHLIGHT = 0x100;
+
     /* End of masks for mPrivateFlags4 */
 
     /** @hide */
@@ -9170,6 +9176,13 @@
     }
 
     /**
+     * @hide
+     */
+    public boolean hideAutofillHighlight() {
+        return (mPrivateFlags4 & PFLAG4_AUTOFILL_HIDE_HIGHLIGHT) != 0;
+    }
+
+    /**
      * Gets the {@link View}'s current autofill value.
      *
      * <p>By default returns {@code null}, but subclasses should override it and return an
@@ -11750,7 +11763,7 @@
      * @hide
      */
     @TestApi
-    public void setAutofilled(boolean isAutofilled) {
+    public void setAutofilled(boolean isAutofilled, boolean hideHighlight) {
         boolean wasChanged = isAutofilled != isAutofilled();
 
         if (wasChanged) {
@@ -11760,6 +11773,12 @@
                 mPrivateFlags3 &= ~PFLAG3_IS_AUTOFILLED;
             }
 
+            if (hideHighlight) {
+                mPrivateFlags4 |= PFLAG4_AUTOFILL_HIDE_HIGHLIGHT;
+            } else {
+                mPrivateFlags4 &= ~PFLAG4_AUTOFILL_HIDE_HIGHLIGHT;
+            }
+
             invalidate();
         }
     }
@@ -20578,6 +20597,7 @@
 
             state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
             state.mIsAutofilled = isAutofilled();
+            state.mHideHighlight = hideAutofillHighlight();
             state.mAutofillViewId = mAutofillViewId;
             return state;
         }
@@ -20654,7 +20674,7 @@
                 mStartActivityRequestWho = baseState.mStartActivityRequestWhoSaved;
             }
             if ((baseState.mSavedData & BaseSavedState.IS_AUTOFILLED) != 0) {
-                setAutofilled(baseState.mIsAutofilled);
+                setAutofilled(baseState.mIsAutofilled, baseState.mHideHighlight);
             }
             if ((baseState.mSavedData & BaseSavedState.AUTOFILL_ID) != 0) {
                 // It can happen that views have the same view id and the restoration path will not
@@ -24087,12 +24107,13 @@
     }
 
     /**
-     * Draw {@link View#isAutofilled()} highlight over view if the view is autofilled.
+     * Draw {@link View#isAutofilled()} highlight over view if the view is autofilled, unless
+     * {@link #PFLAG4_AUTOFILL_HIDE_HIGHLIGHT} is enabled.
      *
      * @param canvas The canvas to draw on
      */
     private void drawAutofilledHighlight(@NonNull Canvas canvas) {
-        if (isAutofilled()) {
+        if (isAutofilled() && !hideAutofillHighlight()) {
             Drawable autofilledHighlight = getAutofilledDrawable();
 
             if (autofilledHighlight != null) {
@@ -28535,6 +28556,7 @@
         int mSavedData;
         String mStartActivityRequestWhoSaved;
         boolean mIsAutofilled;
+        boolean mHideHighlight;
         int mAutofillViewId;
 
         /**
@@ -28558,6 +28580,7 @@
             mSavedData = source.readInt();
             mStartActivityRequestWhoSaved = source.readString();
             mIsAutofilled = source.readBoolean();
+            mHideHighlight = source.readBoolean();
             mAutofillViewId = source.readInt();
         }
 
@@ -28577,6 +28600,7 @@
             out.writeInt(mSavedData);
             out.writeString(mStartActivityRequestWhoSaved);
             out.writeBoolean(mIsAutofilled);
+            out.writeBoolean(mHideHighlight);
             out.writeInt(mAutofillViewId);
         }
 
diff --git a/core/java/android/view/autofill/AutofillManager.java b/core/java/android/view/autofill/AutofillManager.java
index dda4e8b..39a9ed4 100644
--- a/core/java/android/view/autofill/AutofillManager.java
+++ b/core/java/android/view/autofill/AutofillManager.java
@@ -1236,7 +1236,7 @@
             // If the session is gone some fields might still be highlighted, hence we have to
             // remove the isAutofilled property even if no sessions are active.
             if (mLastAutofilledData == null) {
-                view.setAutofilled(false);
+                view.setAutofilled(false, false);
             } else {
                 id = view.getAutofillId();
                 if (mLastAutofilledData.containsKey(id)) {
@@ -1244,13 +1244,13 @@
                     valueWasRead = true;
 
                     if (Objects.equals(mLastAutofilledData.get(id), value)) {
-                        view.setAutofilled(true);
+                        view.setAutofilled(true, false);
                     } else {
-                        view.setAutofilled(false);
+                        view.setAutofilled(false, false);
                         mLastAutofilledData.remove(id);
                     }
                 } else {
-                    view.setAutofilled(false);
+                    view.setAutofilled(false, false);
                 }
             }
 
@@ -2166,7 +2166,8 @@
      * @param view The view that is to be autofilled
      * @param targetValue The value we want to fill into view
      */
-    private void setAutofilledIfValuesIs(@NonNull View view, @Nullable AutofillValue targetValue) {
+    private void setAutofilledIfValuesIs(@NonNull View view, @Nullable AutofillValue targetValue,
+            boolean hideHighlight) {
         AutofillValue currentValue = view.getAutofillValue();
         if (Objects.equals(currentValue, targetValue)) {
             synchronized (mLock) {
@@ -2175,11 +2176,12 @@
                 }
                 mLastAutofilledData.put(view.getAutofillId(), targetValue);
             }
-            view.setAutofilled(true);
+            view.setAutofilled(true, hideHighlight);
         }
     }
 
-    private void autofill(int sessionId, List<AutofillId> ids, List<AutofillValue> values) {
+    private void autofill(int sessionId, List<AutofillId> ids, List<AutofillValue> values,
+            boolean hideHighlight) {
         synchronized (mLock) {
             if (sessionId != mSessionId) {
                 return;
@@ -2238,7 +2240,7 @@
                     // synchronously.
                     // If autofill happens async, the view is set to autofilled in
                     // notifyValueChanged.
-                    setAutofilledIfValuesIs(view, value);
+                    setAutofilledIfValuesIs(view, value, hideHighlight);
 
                     numApplied++;
                 }
@@ -3256,10 +3258,11 @@
         }
 
         @Override
-        public void autofill(int sessionId, List<AutofillId> ids, List<AutofillValue> values) {
+        public void autofill(int sessionId, List<AutofillId> ids, List<AutofillValue> values,
+                boolean hideHighlight) {
             final AutofillManager afm = mAfm.get();
             if (afm != null) {
-                afm.post(() -> afm.autofill(sessionId, ids, values));
+                afm.post(() -> afm.autofill(sessionId, ids, values, hideHighlight));
             }
         }
 
@@ -3397,10 +3400,11 @@
         }
 
         @Override
-        public void autofill(int sessionId, List<AutofillId> ids, List<AutofillValue> values) {
+        public void autofill(int sessionId, List<AutofillId> ids, List<AutofillValue> values,
+                boolean hideHighlight) {
             final AutofillManager afm = mAfm.get();
             if (afm != null) {
-                afm.post(() -> afm.autofill(sessionId, ids, values));
+                afm.post(() -> afm.autofill(sessionId, ids, values, hideHighlight));
             }
         }
 
diff --git a/core/java/android/view/autofill/IAugmentedAutofillManagerClient.aidl b/core/java/android/view/autofill/IAugmentedAutofillManagerClient.aidl
index 03054df..8526c1e 100644
--- a/core/java/android/view/autofill/IAugmentedAutofillManagerClient.aidl
+++ b/core/java/android/view/autofill/IAugmentedAutofillManagerClient.aidl
@@ -38,7 +38,8 @@
     /**
      * Autofills the activity with the contents of the values.
      */
-    void autofill(int sessionId, in List<AutofillId> ids, in List<AutofillValue> values);
+    void autofill(int sessionId, in List<AutofillId> ids, in List<AutofillValue> values,
+            boolean hideHighlight);
 
     /**
       * Requests showing the fill UI.
diff --git a/core/java/android/view/autofill/IAutoFillManagerClient.aidl b/core/java/android/view/autofill/IAutoFillManagerClient.aidl
index 3903665..4371b3c 100644
--- a/core/java/android/view/autofill/IAutoFillManagerClient.aidl
+++ b/core/java/android/view/autofill/IAutoFillManagerClient.aidl
@@ -44,7 +44,8 @@
     /**
       * Autofills the activity with the contents of a dataset.
       */
-    void autofill(int sessionId, in List<AutofillId> ids, in List<AutofillValue> values);
+    void autofill(int sessionId, in List<AutofillId> ids, in List<AutofillValue> values,
+            boolean hideHighlight);
 
     /**
       * Authenticates a fill response or a data set.
diff --git a/core/java/android/view/inputmethod/InlineSuggestion.java b/core/java/android/view/inputmethod/InlineSuggestion.java
index 6500613..dd1738a 100644
--- a/core/java/android/view/inputmethod/InlineSuggestion.java
+++ b/core/java/android/view/inputmethod/InlineSuggestion.java
@@ -16,6 +16,7 @@
 
 package android.view.inputmethod;
 
+import android.annotation.BinderThread;
 import android.annotation.CallbackExecutor;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
@@ -94,19 +95,21 @@
     }
 
 
-
     /**
      * Inflates a view with the content of this suggestion at a specific size.
      * The size must be between the {@link InlinePresentationSpec#getMinSize() min size}
      * and the {@link InlinePresentationSpec#getMaxSize() max size} of the presentation
      * spec returned by {@link InlineSuggestionInfo#getPresentationSpec()}.
      *
-     * @param context Context in which to inflate the view.
-     * @param size The size at which to inflate the suggestion.
-     * @param callback Callback for receiving the inflated view.
+     * <p> The caller can attach an {@link View.OnClickListener} and/or an
+     * {@link View.OnLongClickListener} to the view in the {@code callback} to receive click and
+     * long click events on the view.
      *
+     * @param context  Context in which to inflate the view.
+     * @param size     The size at which to inflate the suggestion.
+     * @param callback Callback for receiving the inflated view.
      * @throws IllegalArgumentException If an invalid argument is passed.
-     * @throws IllegalStateException if this method is already called.
+     * @throws IllegalStateException    If this method is already called.
      */
     public void inflate(@NonNull Context context, @NonNull Size size,
             @NonNull @CallbackExecutor Executor callbackExecutor,
@@ -151,12 +154,31 @@
         }
 
         @Override
+        @BinderThread
         public void onContent(SurfaceControlViewHost.SurfacePackage content) {
             final InlineContentCallbackImpl callbackImpl = mCallbackImpl.get();
             if (callbackImpl != null) {
                 callbackImpl.onContent(content);
             }
         }
+
+        @Override
+        @BinderThread
+        public void onClick() {
+            final InlineContentCallbackImpl callbackImpl = mCallbackImpl.get();
+            if (callbackImpl != null) {
+                callbackImpl.onClick();
+            }
+        }
+
+        @Override
+        @BinderThread
+        public void onLongClick() {
+            final InlineContentCallbackImpl callbackImpl = mCallbackImpl.get();
+            if (callbackImpl != null) {
+                callbackImpl.onLongClick();
+            }
+        }
     }
 
     private static final class InlineContentCallbackImpl {
@@ -164,6 +186,7 @@
         private final @NonNull Context mContext;
         private final @NonNull Executor mCallbackExecutor;
         private final @NonNull Consumer<View> mCallback;
+        private @Nullable View mView;
 
         InlineContentCallbackImpl(@NonNull Context context,
                 @NonNull @CallbackExecutor Executor callbackExecutor,
@@ -173,12 +196,27 @@
             mCallback = callback;
         }
 
+        @BinderThread
         public void onContent(SurfaceControlViewHost.SurfacePackage content) {
             if (content == null) {
                 mCallbackExecutor.execute(() -> mCallback.accept(/* view */null));
             } else {
-                mCallbackExecutor.execute(
-                        () -> mCallback.accept(new InlineContentView(mContext, content)));
+                mView = new InlineContentView(mContext, content);
+                mCallbackExecutor.execute(() -> mCallback.accept(mView));
+            }
+        }
+
+        @BinderThread
+        public void onClick() {
+            if (mView != null && mView.hasOnClickListeners()) {
+                mView.callOnClick();
+            }
+        }
+
+        @BinderThread
+        public void onLongClick() {
+            if (mView != null && mView.hasOnLongClickListeners()) {
+                mView.performLongClick();
             }
         }
     }
@@ -201,7 +239,7 @@
 
 
 
-    // Code below generated by codegen v1.0.14.
+    // Code below generated by codegen v1.0.15.
     //
     // DO NOT MODIFY!
     // CHECKSTYLE:OFF Generated code
@@ -360,8 +398,8 @@
     };
 
     @DataClass.Generated(
-            time = 1581929285156L,
-            codegenVersion = "1.0.14",
+            time = 1583889058241L,
+            codegenVersion = "1.0.15",
             sourceFile = "frameworks/base/core/java/android/view/inputmethod/InlineSuggestion.java",
             inputSignatures = "private static final  java.lang.String TAG\nprivate final @android.annotation.NonNull android.view.inputmethod.InlineSuggestionInfo mInfo\nprivate final @android.annotation.Nullable com.android.internal.view.inline.IInlineContentProvider mContentProvider\nprivate @com.android.internal.util.DataClass.ParcelWith(android.view.inputmethod.InlineSuggestion.InlineContentCallbackImplParceling.class) @android.annotation.Nullable android.view.inputmethod.InlineSuggestion.InlineContentCallbackImpl mInlineContentCallback\npublic static @android.annotation.TestApi @android.annotation.NonNull android.view.inputmethod.InlineSuggestion newInlineSuggestion(android.view.inputmethod.InlineSuggestionInfo)\npublic  void inflate(android.content.Context,android.util.Size,java.util.concurrent.Executor,java.util.function.Consumer<android.view.View>)\nprivate synchronized  android.view.inputmethod.InlineSuggestion.InlineContentCallbackImpl getInlineContentCallback(android.content.Context,java.util.concurrent.Executor,java.util.function.Consumer<android.view.View>)\nclass InlineSuggestion extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true, genToString=true, genHiddenConstDefs=true, genHiddenConstructor=true)")
     @Deprecated
diff --git a/core/java/android/view/textclassifier/ConversationActions.java b/core/java/android/view/textclassifier/ConversationActions.java
index 6246b50..842ba29 100644
--- a/core/java/android/view/textclassifier/ConversationActions.java
+++ b/core/java/android/view/textclassifier/ConversationActions.java
@@ -21,15 +21,12 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.StringDef;
-import android.annotation.UserIdInt;
 import android.app.Person;
 import android.os.Bundle;
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.os.UserHandle;
 import android.text.SpannedString;
 
-import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.Preconditions;
 
 import java.lang.annotation.Retention;
@@ -317,13 +314,9 @@
         @NonNull
         @Hint
         private final List<String> mHints;
-        @Nullable
-        private String mCallingPackageName;
-        @UserIdInt
-        private int mUserId = UserHandle.USER_NULL;
         @NonNull
         private Bundle mExtras;
-        private boolean mUseDefaultTextClassifier;
+        @Nullable private SystemTextClassifierMetadata mSystemTcMetadata;
 
         private Request(
                 @NonNull List<Message> conversation,
@@ -345,10 +338,8 @@
             int maxSuggestions = in.readInt();
             List<String> hints = new ArrayList<>();
             in.readStringList(hints);
-            String callingPackageName = in.readString();
-            int userId = in.readInt();
             Bundle extras = in.readBundle();
-            boolean useDefaultTextClassifier = in.readBoolean();
+            SystemTextClassifierMetadata systemTcMetadata = in.readParcelable(null);
 
             Request request = new Request(
                     conversation,
@@ -356,9 +347,7 @@
                     maxSuggestions,
                     hints,
                     extras);
-            request.setCallingPackageName(callingPackageName);
-            request.setUserId(userId);
-            request.setUseDefaultTextClassifier(useDefaultTextClassifier);
+            request.setSystemTextClassifierMetadata(systemTcMetadata);
             return request;
         }
 
@@ -368,10 +357,8 @@
             parcel.writeParcelable(mTypeConfig, flags);
             parcel.writeInt(mMaxSuggestions);
             parcel.writeStringList(mHints);
-            parcel.writeString(mCallingPackageName);
-            parcel.writeInt(mUserId);
             parcel.writeBundle(mExtras);
-            parcel.writeBoolean(mUseDefaultTextClassifier);
+            parcel.writeParcelable(mSystemTcMetadata, flags);
         }
 
         @Override
@@ -421,62 +408,31 @@
         }
 
         /**
-         * Sets the name of the package that is sending this request.
-         * <p>
-         * Package-private for SystemTextClassifier's use.
-         * @hide
-         */
-        @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
-        public void setCallingPackageName(@Nullable String callingPackageName) {
-            mCallingPackageName = callingPackageName;
-        }
-
-        /**
          * Returns the name of the package that sent this request.
          * This returns {@code null} if no calling package name is set.
          */
         @Nullable
         public String getCallingPackageName() {
-            return mCallingPackageName;
+            return mSystemTcMetadata != null ? mSystemTcMetadata.getCallingPackageName() : null;
         }
 
         /**
-         * Sets the id of the user that sent this request.
-         * <p>
-         * Package-private for SystemTextClassifier's use.
-         * @hide
-         */
-        void setUserId(@UserIdInt int userId) {
-            mUserId = userId;
-        }
-
-        /**
-         * Returns the id of the user that sent this request.
-         * @hide
-         */
-        @UserIdInt
-        public int getUserId() {
-            return mUserId;
-        }
-
-        /**
-         * Sets whether to use the default text classifier to handle this request.
-         * This will be ignored if it is not the system text classifier to handle this request.
+         * Sets the information about the {@link SystemTextClassifier} that sent this request.
          *
          * @hide
          */
-        void setUseDefaultTextClassifier(boolean useDefaultTextClassifier) {
-            mUseDefaultTextClassifier = useDefaultTextClassifier;
+        void setSystemTextClassifierMetadata(@Nullable SystemTextClassifierMetadata systemTcData) {
+            mSystemTcMetadata = systemTcData;
         }
 
         /**
-         * Returns whether to use the default text classifier to handle this request. This
-         * will be ignored if it is not the system text classifier to handle this request.
+         * Returns the information about the {@link SystemTextClassifier} that sent this request.
          *
          * @hide
          */
-        public boolean getUseDefaultTextClassifier() {
-            return mUseDefaultTextClassifier;
+        @Nullable
+        public SystemTextClassifierMetadata getSystemTextClassifierMetadata() {
+            return mSystemTcMetadata;
         }
 
         /**
diff --git a/core/java/android/view/textclassifier/SelectionEvent.java b/core/java/android/view/textclassifier/SelectionEvent.java
index e0f29a9..9a54544 100644
--- a/core/java/android/view/textclassifier/SelectionEvent.java
+++ b/core/java/android/view/textclassifier/SelectionEvent.java
@@ -19,10 +19,8 @@
 import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.annotation.UserIdInt;
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.os.UserHandle;
 import android.view.textclassifier.TextClassifier.EntityType;
 import android.view.textclassifier.TextClassifier.WidgetType;
 
@@ -129,7 +127,6 @@
     private String mWidgetType = TextClassifier.WIDGET_TYPE_UNKNOWN;
     private @InvocationMethod int mInvocationMethod;
     @Nullable private String mWidgetVersion;
-    private @UserIdInt int mUserId = UserHandle.USER_NULL;
     @Nullable private String mResultId;
     private long mEventTime;
     private long mDurationSinceSessionStart;
@@ -140,7 +137,7 @@
     private int mEnd;
     private int mSmartStart;
     private int mSmartEnd;
-    private boolean mUseDefaultTextClassifier;
+    @Nullable private SystemTextClassifierMetadata mSystemTcMetadata;
 
     SelectionEvent(
             int start, int end,
@@ -161,6 +158,7 @@
         mEventType = in.readInt();
         mEntityType = in.readString();
         mWidgetVersion = in.readInt() > 0 ? in.readString() : null;
+        // TODO: remove mPackageName once aiai does not need it
         mPackageName = in.readString();
         mWidgetType = in.readString();
         mInvocationMethod = in.readInt();
@@ -175,8 +173,7 @@
         mEnd = in.readInt();
         mSmartStart = in.readInt();
         mSmartEnd = in.readInt();
-        mUserId = in.readInt();
-        mUseDefaultTextClassifier = in.readBoolean();
+        mSystemTcMetadata = in.readParcelable(null);
     }
 
     @Override
@@ -189,6 +186,7 @@
         if (mWidgetVersion != null) {
             dest.writeString(mWidgetVersion);
         }
+        // TODO: remove mPackageName once aiai does not need it
         dest.writeString(mPackageName);
         dest.writeString(mWidgetType);
         dest.writeInt(mInvocationMethod);
@@ -205,8 +203,7 @@
         dest.writeInt(mEnd);
         dest.writeInt(mSmartStart);
         dest.writeInt(mSmartEnd);
-        dest.writeInt(mUserId);
-        dest.writeBoolean(mUseDefaultTextClassifier);
+        dest.writeParcelable(mSystemTcMetadata, flags);
     }
 
     @Override
@@ -409,45 +406,26 @@
      */
     @NonNull
     public String getPackageName() {
-        return mPackageName;
+        return mSystemTcMetadata != null ? mSystemTcMetadata.getCallingPackageName() : "";
     }
 
     /**
-     * Sets the id of this event's user.
-     * <p>
-     * Package-private for SystemTextClassifier's use.
-     */
-    void setUserId(@UserIdInt int userId) {
-        mUserId = userId;
-    }
-
-    /**
-     * Returns the id of this event's user.
-     * @hide
-     */
-    @UserIdInt
-    public int getUserId() {
-        return mUserId;
-    }
-
-    /**
-     * Sets whether to use the default text classifier to handle this request.
-     * This will be ignored if it is not the system text classifier to handle this request.
+     * Sets the information about the {@link SystemTextClassifier} that sent this request.
      *
      * @hide
      */
-    void setUseDefaultTextClassifier(boolean useDefaultTextClassifier) {
-        mUseDefaultTextClassifier = useDefaultTextClassifier;
+    void setSystemTextClassifierMetadata(@Nullable SystemTextClassifierMetadata systemTcMetadata) {
+        mSystemTcMetadata = systemTcMetadata;
     }
 
     /**
-     * Returns whether to use the default text classifier to handle this request. This
-     * will be ignored if it is not the system text classifier to handle this request.
+     * Returns the information about the {@link SystemTextClassifier} that sent this request.
      *
      * @hide
      */
-    public boolean getUseDefaultTextClassifier() {
-        return mUseDefaultTextClassifier;
+    @Nullable
+    public SystemTextClassifierMetadata getSystemTextClassifierMetadata() {
+        return mSystemTcMetadata;
     }
 
     /**
@@ -476,7 +454,7 @@
         mPackageName = context.getPackageName();
         mWidgetType = context.getWidgetType();
         mWidgetVersion = context.getWidgetVersion();
-        mUserId = context.getUserId();
+        mSystemTcMetadata = context.getSystemTextClassifierMetadata();
     }
 
     /**
@@ -663,10 +641,9 @@
     @Override
     public int hashCode() {
         return Objects.hash(mAbsoluteStart, mAbsoluteEnd, mEventType, mEntityType,
-                mWidgetVersion, mPackageName, mUserId, mWidgetType, mInvocationMethod, mResultId,
+                mWidgetVersion, mPackageName, mWidgetType, mInvocationMethod, mResultId,
                 mEventTime, mDurationSinceSessionStart, mDurationSincePreviousEvent,
-                mEventIndex, mSessionId, mStart, mEnd, mSmartStart, mSmartEnd,
-                mUseDefaultTextClassifier);
+                mEventIndex, mSessionId, mStart, mEnd, mSmartStart, mSmartEnd, mSystemTcMetadata);
     }
 
     @Override
@@ -685,7 +662,6 @@
                 && Objects.equals(mEntityType, other.mEntityType)
                 && Objects.equals(mWidgetVersion, other.mWidgetVersion)
                 && Objects.equals(mPackageName, other.mPackageName)
-                && mUserId == other.mUserId
                 && Objects.equals(mWidgetType, other.mWidgetType)
                 && mInvocationMethod == other.mInvocationMethod
                 && Objects.equals(mResultId, other.mResultId)
@@ -698,7 +674,7 @@
                 && mEnd == other.mEnd
                 && mSmartStart == other.mSmartStart
                 && mSmartEnd == other.mSmartEnd
-                && mUseDefaultTextClassifier == other.mUseDefaultTextClassifier;
+                && mSystemTcMetadata == other.mSystemTcMetadata;
     }
 
     @Override
@@ -706,15 +682,14 @@
         return String.format(Locale.US,
                 "SelectionEvent {absoluteStart=%d, absoluteEnd=%d, eventType=%d, entityType=%s, "
                         + "widgetVersion=%s, packageName=%s, widgetType=%s, invocationMethod=%s, "
-                        + "userId=%d, resultId=%s, eventTime=%d, durationSinceSessionStart=%d, "
+                        + "resultId=%s, eventTime=%d, durationSinceSessionStart=%d, "
                         + "durationSincePreviousEvent=%d, eventIndex=%d,"
                         + "sessionId=%s, start=%d, end=%d, smartStart=%d, smartEnd=%d, "
-                        + "mUseDefaultTextClassifier=%b}",
+                        + "systemTcMetadata=%s}",
                 mAbsoluteStart, mAbsoluteEnd, mEventType, mEntityType,
                 mWidgetVersion, mPackageName, mWidgetType, mInvocationMethod,
-                mUserId, mResultId, mEventTime, mDurationSinceSessionStart,
-                mDurationSincePreviousEvent, mEventIndex,
-                mSessionId, mStart, mEnd, mSmartStart, mSmartEnd, mUseDefaultTextClassifier);
+                mResultId, mEventTime, mDurationSinceSessionStart, mDurationSincePreviousEvent,
+                mEventIndex, mSessionId, mStart, mEnd, mSmartStart, mSmartEnd, mSystemTcMetadata);
     }
 
     public static final @android.annotation.NonNull Creator<SelectionEvent> CREATOR = new Creator<SelectionEvent>() {
diff --git a/core/java/android/view/textclassifier/SystemTextClassifier.java b/core/java/android/view/textclassifier/SystemTextClassifier.java
index fe5e8d6..86ef4e1 100644
--- a/core/java/android/view/textclassifier/SystemTextClassifier.java
+++ b/core/java/android/view/textclassifier/SystemTextClassifier.java
@@ -18,7 +18,6 @@
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.annotation.UserIdInt;
 import android.annotation.WorkerThread;
 import android.content.Context;
 import android.os.Bundle;
@@ -39,7 +38,8 @@
 import java.util.concurrent.TimeUnit;
 
 /**
- * Proxy to the system's default TextClassifier.
+ * proxy to the request to TextClassifierService via the TextClassificationManagerService.
+ *
  * @hide
  */
 @VisibleForTesting(visibility = Visibility.PACKAGE)
@@ -50,14 +50,19 @@
     private final ITextClassifierService mManagerService;
     private final TextClassificationConstants mSettings;
     private final TextClassifier mFallback;
-    private final String mPackageName;
-    // NOTE: Always set this before sending a request to the manager service otherwise the manager
-    // service will throw a remote exception.
-    @UserIdInt
-    private final int mUserId;
-    private final boolean mUseDefault;
     private TextClassificationSessionId mSessionId;
+    // NOTE: Always set this before sending a request to the manager service otherwise the
+    // manager service will throw a remote exception.
+    @NonNull
+    private final SystemTextClassifierMetadata mSystemTcMetadata;
 
+    /**
+     * Constructor of {@link SystemTextClassifier}
+     *
+     * @param context the context of the request.
+     * @param settings TextClassifier specific settings.
+     * @param useDefault whether to use the default text classifier to handle this request
+     */
     public SystemTextClassifier(
             Context context,
             TextClassificationConstants settings,
@@ -66,9 +71,11 @@
                 ServiceManager.getServiceOrThrow(Context.TEXT_CLASSIFICATION_SERVICE));
         mSettings = Objects.requireNonNull(settings);
         mFallback = TextClassifier.NO_OP;
-        mPackageName = Objects.requireNonNull(context.getOpPackageName());
-        mUserId = context.getUserId();
-        mUseDefault = useDefault;
+        // NOTE: Always set this before sending a request to the manager service otherwise the
+        // manager service will throw a remote exception.
+        mSystemTcMetadata = new SystemTextClassifierMetadata(
+                Objects.requireNonNull(context.getOpPackageName()), context.getUserId(),
+                useDefault);
     }
 
     /**
@@ -80,9 +87,7 @@
         Objects.requireNonNull(request);
         Utils.checkMainThread();
         try {
-            request.setCallingPackageName(mPackageName);
-            request.setUserId(mUserId);
-            request.setUseDefaultTextClassifier(mUseDefault);
+            request.setSystemTextClassifierMetadata(mSystemTcMetadata);
             final BlockingCallback<TextSelection> callback =
                     new BlockingCallback<>("textselection");
             mManagerService.onSuggestSelection(mSessionId, request, callback);
@@ -105,9 +110,7 @@
         Objects.requireNonNull(request);
         Utils.checkMainThread();
         try {
-            request.setCallingPackageName(mPackageName);
-            request.setUserId(mUserId);
-            request.setUseDefaultTextClassifier(mUseDefault);
+            request.setSystemTextClassifierMetadata(mSystemTcMetadata);
             final BlockingCallback<TextClassification> callback =
                     new BlockingCallback<>("textclassification");
             mManagerService.onClassifyText(mSessionId, request, callback);
@@ -137,9 +140,7 @@
         }
 
         try {
-            request.setCallingPackageName(mPackageName);
-            request.setUserId(mUserId);
-            request.setUseDefaultTextClassifier(mUseDefault);
+            request.setSystemTextClassifierMetadata(mSystemTcMetadata);
             final BlockingCallback<TextLinks> callback =
                     new BlockingCallback<>("textlinks");
             mManagerService.onGenerateLinks(mSessionId, request, callback);
@@ -159,8 +160,7 @@
         Utils.checkMainThread();
 
         try {
-            event.setUserId(mUserId);
-            event.setUseDefaultTextClassifier(mUseDefault);
+            event.setSystemTextClassifierMetadata(mSystemTcMetadata);
             mManagerService.onSelectionEvent(mSessionId, event);
         } catch (RemoteException e) {
             Log.e(LOG_TAG, "Error reporting selection event.", e);
@@ -173,12 +173,11 @@
         Utils.checkMainThread();
 
         try {
-            final TextClassificationContext tcContext = event.getEventContext() == null
-                    ? new TextClassificationContext.Builder(mPackageName, WIDGET_TYPE_UNKNOWN)
-                            .build()
-                    : event.getEventContext();
-            tcContext.setUserId(mUserId);
-            tcContext.setUseDefaultTextClassifier(mUseDefault);
+            final TextClassificationContext tcContext =
+                    event.getEventContext() == null ? new TextClassificationContext.Builder(
+                            mSystemTcMetadata.getCallingPackageName(), WIDGET_TYPE_UNKNOWN).build()
+                            : event.getEventContext();
+            tcContext.setSystemTextClassifierMetadata(mSystemTcMetadata);
             event.setEventContext(tcContext);
             mManagerService.onTextClassifierEvent(mSessionId, event);
         } catch (RemoteException e) {
@@ -192,9 +191,7 @@
         Utils.checkMainThread();
 
         try {
-            request.setCallingPackageName(mPackageName);
-            request.setUserId(mUserId);
-            request.setUseDefaultTextClassifier(mUseDefault);
+            request.setSystemTextClassifierMetadata(mSystemTcMetadata);
             final BlockingCallback<TextLanguage> callback =
                     new BlockingCallback<>("textlanguage");
             mManagerService.onDetectLanguage(mSessionId, request, callback);
@@ -214,9 +211,7 @@
         Utils.checkMainThread();
 
         try {
-            request.setCallingPackageName(mPackageName);
-            request.setUserId(mUserId);
-            request.setUseDefaultTextClassifier(mUseDefault);
+            request.setSystemTextClassifierMetadata(mSystemTcMetadata);
             final BlockingCallback<ConversationActions> callback =
                     new BlockingCallback<>("conversation-actions");
             mManagerService.onSuggestConversationActions(mSessionId, request, callback);
@@ -256,10 +251,8 @@
         printWriter.println("SystemTextClassifier:");
         printWriter.increaseIndent();
         printWriter.printPair("mFallback", mFallback);
-        printWriter.printPair("mPackageName", mPackageName);
         printWriter.printPair("mSessionId", mSessionId);
-        printWriter.printPair("mUserId", mUserId);
-        printWriter.printPair("mUseDefault",  mUseDefault);
+        printWriter.printPair("mSystemTcMetadata",  mSystemTcMetadata);
         printWriter.decreaseIndent();
         printWriter.println();
     }
@@ -275,7 +268,7 @@
             @NonNull TextClassificationSessionId sessionId) {
         mSessionId = Objects.requireNonNull(sessionId);
         try {
-            classificationContext.setUserId(mUserId);
+            classificationContext.setSystemTextClassifierMetadata(mSystemTcMetadata);
             mManagerService.onCreateTextClassificationSession(classificationContext, mSessionId);
         } catch (RemoteException e) {
             Log.e(LOG_TAG, "Error starting a new classification session.", e);
diff --git a/core/java/android/view/textclassifier/SystemTextClassifierMetadata.aidl b/core/java/android/view/textclassifier/SystemTextClassifierMetadata.aidl
new file mode 100644
index 0000000..4d4e90a
--- /dev/null
+++ b/core/java/android/view/textclassifier/SystemTextClassifierMetadata.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2020 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.view.textclassifier;
+
+parcelable SystemTextClassifierMetadata;
\ No newline at end of file
diff --git a/core/java/android/view/textclassifier/SystemTextClassifierMetadata.java b/core/java/android/view/textclassifier/SystemTextClassifierMetadata.java
new file mode 100644
index 0000000..971e3e2
--- /dev/null
+++ b/core/java/android/view/textclassifier/SystemTextClassifierMetadata.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2020 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.view.textclassifier;
+
+import android.annotation.NonNull;
+import android.annotation.UserIdInt;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.annotations.VisibleForTesting.Visibility;
+
+import java.util.Locale;
+import java.util.Objects;
+
+/**
+ * SystemTextClassifier specific information.
+ * <p>
+ * This contains information requires for the TextClassificationManagerService to process the
+ * requests from the application, e.g. user id, calling package name and etc. Centrialize the data
+ * into this class helps to extend the scalability if we want to add new fields.
+ * @hide
+ */
+@VisibleForTesting(visibility = Visibility.PACKAGE)
+public final class SystemTextClassifierMetadata implements Parcelable {
+
+    /* The name of the package that sent the TC request. */
+    @NonNull
+    private final String mCallingPackageName;
+    /* The id of the user that sent the TC request. */
+    @UserIdInt
+    private final int mUserId;
+    /* Whether to use the default text classifier to handle the request. */
+    private final boolean mUseDefaultTextClassifier;
+
+    public SystemTextClassifierMetadata(@NonNull String packageName, @UserIdInt int userId,
+            boolean useDefaultTextClassifier) {
+        Objects.requireNonNull(packageName);
+        mCallingPackageName = packageName;
+        mUserId = userId;
+        mUseDefaultTextClassifier = useDefaultTextClassifier;
+    }
+
+    /**
+     * Returns the id of the user that sent the TC request.
+     */
+    @UserIdInt
+    public int getUserId() {
+        return mUserId;
+    }
+
+    /**
+     * Returns the name of the package that sent the TC request.
+     * This returns {@code null} if no calling package name is set.
+     */
+    @NonNull
+    public String getCallingPackageName() {
+        return mCallingPackageName;
+    }
+
+    /**
+     * Returns whether to use the default text classifier to handle TC request.
+     */
+    public boolean useDefaultTextClassifier() {
+        return mUseDefaultTextClassifier;
+    }
+
+    @Override
+    public String toString() {
+        return String.format(Locale.US,
+                "SystemTextClassifierMetadata {callingPackageName=%s, userId=%d, "
+                        + "useDefaultTextClassifier=%b}",
+                mCallingPackageName, mUserId, mUseDefaultTextClassifier);
+    }
+
+    private static SystemTextClassifierMetadata readFromParcel(Parcel in) {
+        final String packageName = in.readString();
+        final int userId = in.readInt();
+        final boolean useDefaultTextClassifier = in.readBoolean();
+        return new SystemTextClassifierMetadata(packageName, userId, useDefaultTextClassifier);
+    }
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeString(mCallingPackageName);
+        dest.writeInt(mUserId);
+        dest.writeBoolean(mUseDefaultTextClassifier);
+    }
+
+    public static final @NonNull Creator<SystemTextClassifierMetadata> CREATOR =
+            new Creator<SystemTextClassifierMetadata>() {
+        @Override
+        public SystemTextClassifierMetadata createFromParcel(Parcel in) {
+            return readFromParcel(in);
+        }
+
+        @Override
+        public SystemTextClassifierMetadata[] newArray(int size) {
+            return new SystemTextClassifierMetadata[size];
+        }
+    };
+}
diff --git a/core/java/android/view/textclassifier/TextClassification.java b/core/java/android/view/textclassifier/TextClassification.java
index 00f762b..8b9d129 100644
--- a/core/java/android/view/textclassifier/TextClassification.java
+++ b/core/java/android/view/textclassifier/TextClassification.java
@@ -21,7 +21,6 @@
 import android.annotation.IntRange;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.annotation.UserIdInt;
 import android.app.PendingIntent;
 import android.app.RemoteAction;
 import android.content.Context;
@@ -36,7 +35,6 @@
 import android.os.LocaleList;
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.os.UserHandle;
 import android.text.SpannedString;
 import android.util.ArrayMap;
 import android.view.View.OnClickListener;
@@ -552,10 +550,7 @@
         @Nullable private final LocaleList mDefaultLocales;
         @Nullable private final ZonedDateTime mReferenceTime;
         @NonNull private final Bundle mExtras;
-        @Nullable private String mCallingPackageName;
-        @UserIdInt
-        private int mUserId = UserHandle.USER_NULL;
-        private boolean mUseDefaultTextClassifier;
+        @Nullable private SystemTextClassifierMetadata mSystemTcMetadata;
 
         private Request(
                 CharSequence text,
@@ -616,62 +611,33 @@
         }
 
         /**
-         * Sets the name of the package that is sending this request.
-         * <p>
-         * For SystemTextClassifier's use.
-         * @hide
-         */
-        @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
-        public void setCallingPackageName(@Nullable String callingPackageName) {
-            mCallingPackageName = callingPackageName;
-        }
-
-        /**
          * Returns the name of the package that sent this request.
          * This returns {@code null} if no calling package name is set.
          */
         @Nullable
         public String getCallingPackageName() {
-            return mCallingPackageName;
+            return mSystemTcMetadata != null ? mSystemTcMetadata.getCallingPackageName() : null;
         }
 
         /**
-         * Sets the id of the user that sent this request.
-         * <p>
-         * Package-private for SystemTextClassifier's use.
-         * @hide
-         */
-        void setUserId(@UserIdInt int userId) {
-            mUserId = userId;
-        }
-
-        /**
-         * Returns the id of the user that sent this request.
-         * @hide
-         */
-        @UserIdInt
-        public int getUserId() {
-            return mUserId;
-        }
-
-        /**
-         * Sets whether to use the default text classifier to handle this request.
-         * This will be ignored if it is not the system text classifier to handle this request.
+         * Sets the information about the {@link SystemTextClassifier} that sent this request.
          *
          * @hide
          */
-        void setUseDefaultTextClassifier(boolean useDefaultTextClassifier) {
-            mUseDefaultTextClassifier = useDefaultTextClassifier;
+        @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
+        public void setSystemTextClassifierMetadata(
+                @Nullable SystemTextClassifierMetadata systemTcMetadata) {
+            mSystemTcMetadata = systemTcMetadata;
         }
 
         /**
-         * Returns whether to use the default text classifier to handle this request. This
-         * will be ignored if it is not the system text classifier to handle this request.
+         * Returns the information about the {@link SystemTextClassifier} that sent this request.
          *
          * @hide
          */
-        public boolean getUseDefaultTextClassifier() {
-            return mUseDefaultTextClassifier;
+        @Nullable
+        public SystemTextClassifierMetadata getSystemTextClassifierMetadata() {
+            return mSystemTcMetadata;
         }
 
         /**
@@ -773,10 +739,8 @@
             dest.writeInt(mEndIndex);
             dest.writeParcelable(mDefaultLocales, flags);
             dest.writeString(mReferenceTime == null ? null : mReferenceTime.toString());
-            dest.writeString(mCallingPackageName);
-            dest.writeInt(mUserId);
             dest.writeBundle(mExtras);
-            dest.writeBoolean(mUseDefaultTextClassifier);
+            dest.writeParcelable(mSystemTcMetadata, flags);
         }
 
         private static Request readFromParcel(Parcel in) {
@@ -787,16 +751,12 @@
             final String referenceTimeString = in.readString();
             final ZonedDateTime referenceTime = referenceTimeString == null
                     ? null : ZonedDateTime.parse(referenceTimeString);
-            final String callingPackageName = in.readString();
-            final int userId = in.readInt();
             final Bundle extras = in.readBundle();
-            final boolean useDefaultTextClassifier = in.readBoolean();
+            final SystemTextClassifierMetadata systemTcMetadata = in.readParcelable(null);
 
             final Request request = new Request(text, startIndex, endIndex,
                     defaultLocales, referenceTime, extras);
-            request.setCallingPackageName(callingPackageName);
-            request.setUserId(userId);
-            request.setUseDefaultTextClassifier(useDefaultTextClassifier);
+            request.setSystemTextClassifierMetadata(systemTcMetadata);
             return request;
         }
 
diff --git a/core/java/android/view/textclassifier/TextClassificationContext.java b/core/java/android/view/textclassifier/TextClassificationContext.java
index d58d175..f2323c6 100644
--- a/core/java/android/view/textclassifier/TextClassificationContext.java
+++ b/core/java/android/view/textclassifier/TextClassificationContext.java
@@ -18,10 +18,8 @@
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.annotation.UserIdInt;
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.os.UserHandle;
 import android.view.textclassifier.TextClassifier.WidgetType;
 
 import java.util.Locale;
@@ -33,12 +31,11 @@
  */
 public final class TextClassificationContext implements Parcelable {
 
-    private final String mPackageName;
+    // NOTE: Modify packageName only in the constructor or in setSystemTextClassifierMetadata()
+    private String mPackageName;
     private final String mWidgetType;
     @Nullable private final String mWidgetVersion;
-    @UserIdInt
-    private int mUserId = UserHandle.USER_NULL;
-    private boolean mUseDefaultTextClassifier;
+    private SystemTextClassifierMetadata mSystemTcMetadata;
 
     private TextClassificationContext(
             String packageName,
@@ -58,42 +55,26 @@
     }
 
     /**
-     * Sets the id of this context's user.
-     * <p>
-     * Package-private for SystemTextClassifier's use.
+     * Sets the information about the {@link SystemTextClassifier} that sent this request.
+     *
+     * <p><b>NOTE: </b>This will override the value returned in {@link getPackageName()}.
      * @hide
      */
-    void setUserId(@UserIdInt int userId) {
-        mUserId = userId;
+    void setSystemTextClassifierMetadata(@Nullable SystemTextClassifierMetadata systemTcMetadata) {
+        mSystemTcMetadata = systemTcMetadata;
+        if (mSystemTcMetadata != null) {
+            mPackageName = mSystemTcMetadata.getCallingPackageName();
+        }
     }
 
     /**
-     * Returns the id of this context's user.
-     * @hide
-     */
-    @UserIdInt
-    public int getUserId() {
-        return mUserId;
-    }
-
-    /**
-     * Sets whether to use the default text classifier to handle this request.
-     * This will be ignored if it is not the system text classifier to handle this request.
+     * Returns the information about the {@link SystemTextClassifier} that sent this request.
      *
      * @hide
      */
-    void setUseDefaultTextClassifier(boolean useDefaultTextClassifier) {
-        mUseDefaultTextClassifier = useDefaultTextClassifier;
-    }
-
-    /**
-     * Returns whether to use the default text classifier to handle this request. This
-     * will be ignored if it is not the system text classifier to handle this request.
-     *
-     * @hide
-     */
-    public boolean getUseDefaultTextClassifier() {
-        return mUseDefaultTextClassifier;
+    @Nullable
+    public SystemTextClassifierMetadata getSystemTextClassifierMetadata() {
+        return mSystemTcMetadata;
     }
 
     /**
@@ -118,8 +99,8 @@
     @Override
     public String toString() {
         return String.format(Locale.US, "TextClassificationContext{"
-                + "packageName=%s, widgetType=%s, widgetVersion=%s, userId=%d}",
-                mPackageName, mWidgetType, mWidgetVersion, mUserId);
+                + "packageName=%s, widgetType=%s, widgetVersion=%s, systemTcMetadata=%s}",
+                mPackageName, mWidgetType, mWidgetVersion, mSystemTcMetadata);
     }
 
     /**
@@ -176,16 +157,14 @@
         parcel.writeString(mPackageName);
         parcel.writeString(mWidgetType);
         parcel.writeString(mWidgetVersion);
-        parcel.writeInt(mUserId);
-        parcel.writeBoolean(mUseDefaultTextClassifier);
+        parcel.writeParcelable(mSystemTcMetadata, flags);
     }
 
     private TextClassificationContext(Parcel in) {
         mPackageName = in.readString();
         mWidgetType = in.readString();
         mWidgetVersion = in.readString();
-        mUserId = in.readInt();
-        mUseDefaultTextClassifier = in.readBoolean();
+        mSystemTcMetadata = in.readParcelable(null);
     }
 
     public static final @android.annotation.NonNull Parcelable.Creator<TextClassificationContext> CREATOR =
diff --git a/core/java/android/view/textclassifier/TextLanguage.java b/core/java/android/view/textclassifier/TextLanguage.java
index 58024dc..1e8253d 100644
--- a/core/java/android/view/textclassifier/TextLanguage.java
+++ b/core/java/android/view/textclassifier/TextLanguage.java
@@ -20,12 +20,10 @@
 import android.annotation.IntRange;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.annotation.UserIdInt;
 import android.icu.util.ULocale;
 import android.os.Bundle;
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.os.UserHandle;
 import android.util.ArrayMap;
 
 import com.android.internal.annotations.VisibleForTesting;
@@ -227,10 +225,7 @@
 
         private final CharSequence mText;
         private final Bundle mExtra;
-        @Nullable private String mCallingPackageName;
-        @UserIdInt
-        private int mUserId = UserHandle.USER_NULL;
-        private boolean mUseDefaultTextClassifier;
+        @Nullable private SystemTextClassifierMetadata mSystemTcMetadata;
 
         private Request(CharSequence text, Bundle bundle) {
             mText = text;
@@ -246,61 +241,33 @@
         }
 
         /**
-         * Sets the name of the package that is sending this request.
-         * Package-private for SystemTextClassifier's use.
-         * @hide
-         */
-        @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
-        public void setCallingPackageName(@Nullable String callingPackageName) {
-            mCallingPackageName = callingPackageName;
-        }
-
-        /**
          * Returns the name of the package that sent this request.
          * This returns null if no calling package name is set.
          */
         @Nullable
         public String getCallingPackageName() {
-            return mCallingPackageName;
+            return mSystemTcMetadata != null ? mSystemTcMetadata.getCallingPackageName() : null;
         }
 
         /**
-         * Sets the id of the user that sent this request.
-         * <p>
-         * Package-private for SystemTextClassifier's use.
-         * @hide
-         */
-        void setUserId(@UserIdInt int userId) {
-            mUserId = userId;
-        }
-
-        /**
-         * Returns the id of the user that sent this request.
-         * @hide
-         */
-        @UserIdInt
-        public int getUserId() {
-            return mUserId;
-        }
-
-        /**
-         * Sets whether to use the default text classifier to handle this request.
-         * This will be ignored if it is not the system text classifier to handle this request.
+         * Sets the information about the {@link SystemTextClassifier} that sent this request.
          *
          * @hide
          */
-        void setUseDefaultTextClassifier(boolean useDefaultTextClassifier) {
-            mUseDefaultTextClassifier = useDefaultTextClassifier;
+        @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
+        public void setSystemTextClassifierMetadata(
+                @Nullable SystemTextClassifierMetadata systemTcMetadata) {
+            mSystemTcMetadata = systemTcMetadata;
         }
 
         /**
-         * Returns whether to use the default text classifier to handle this request. This
-         * will be ignored if it is not the system text classifier to handle this request.
+         * Returns the information about the {@link SystemTextClassifier} that sent this request.
          *
          * @hide
          */
-        public boolean getUseDefaultTextClassifier() {
-            return mUseDefaultTextClassifier;
+        @Nullable
+        public SystemTextClassifierMetadata getSystemTextClassifierMetadata() {
+            return mSystemTcMetadata;
         }
 
         /**
@@ -321,23 +288,17 @@
         @Override
         public void writeToParcel(Parcel dest, int flags) {
             dest.writeCharSequence(mText);
-            dest.writeString(mCallingPackageName);
-            dest.writeInt(mUserId);
             dest.writeBundle(mExtra);
-            dest.writeBoolean(mUseDefaultTextClassifier);
+            dest.writeParcelable(mSystemTcMetadata, flags);
         }
 
         private static Request readFromParcel(Parcel in) {
             final CharSequence text = in.readCharSequence();
-            final String callingPackageName = in.readString();
-            final int userId = in.readInt();
             final Bundle extra = in.readBundle();
-            final boolean useDefaultTextClassifier = in.readBoolean();
+            final SystemTextClassifierMetadata systemTcMetadata = in.readParcelable(null);
 
             final Request request = new Request(text, extra);
-            request.setCallingPackageName(callingPackageName);
-            request.setUserId(userId);
-            request.setUseDefaultTextClassifier(useDefaultTextClassifier);
+            request.setSystemTextClassifierMetadata(systemTcMetadata);
             return request;
         }
 
diff --git a/core/java/android/view/textclassifier/TextLinks.java b/core/java/android/view/textclassifier/TextLinks.java
index 7430cb3..dea3a90 100644
--- a/core/java/android/view/textclassifier/TextLinks.java
+++ b/core/java/android/view/textclassifier/TextLinks.java
@@ -20,13 +20,11 @@
 import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.annotation.UserIdInt;
 import android.content.Context;
 import android.os.Bundle;
 import android.os.LocaleList;
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.os.UserHandle;
 import android.text.Spannable;
 import android.text.method.MovementMethod;
 import android.text.style.ClickableSpan;
@@ -340,12 +338,9 @@
         @Nullable private final LocaleList mDefaultLocales;
         @Nullable private final EntityConfig mEntityConfig;
         private final boolean mLegacyFallback;
-        @Nullable private String mCallingPackageName;
         private final Bundle mExtras;
         @Nullable private final ZonedDateTime mReferenceTime;
-        @UserIdInt
-        private int mUserId = UserHandle.USER_NULL;
-        private boolean mUseDefaultTextClassifier;
+        @Nullable private SystemTextClassifierMetadata mSystemTcMetadata;
 
         private Request(
                 CharSequence text,
@@ -409,62 +404,33 @@
         }
 
         /**
-         * Sets the name of the package that is sending this request.
-         * <p>
-         * Package-private for SystemTextClassifier's use.
-         * @hide
-         */
-        @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
-        public void setCallingPackageName(@Nullable String callingPackageName) {
-            mCallingPackageName = callingPackageName;
-        }
-
-        /**
          * Returns the name of the package that sent this request.
          * This returns {@code null} if no calling package name is set.
          */
         @Nullable
         public String getCallingPackageName() {
-            return mCallingPackageName;
+            return mSystemTcMetadata != null ? mSystemTcMetadata.getCallingPackageName() : null;
         }
 
         /**
-         * Sets the id of the user that sent this request.
-         * <p>
-         * Package-private for SystemTextClassifier's use.
-         * @hide
-         */
-        void setUserId(@UserIdInt int userId) {
-            mUserId = userId;
-        }
-
-        /**
-         * Returns the id of the user that sent this request.
-         * @hide
-         */
-        @UserIdInt
-        public int getUserId() {
-            return mUserId;
-        }
-
-        /**
-         * Sets whether to use the default text classifier to handle this request.
-         * This will be ignored if it is not the system text classifier to handle this request.
+         * Sets the information about the {@link SystemTextClassifier} that sent this request.
          *
          * @hide
          */
-        void setUseDefaultTextClassifier(boolean useDefaultTextClassifier) {
-            mUseDefaultTextClassifier = useDefaultTextClassifier;
+        @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
+        public void setSystemTextClassifierMetadata(
+                @Nullable SystemTextClassifierMetadata systemTcMetadata) {
+            mSystemTcMetadata = systemTcMetadata;
         }
 
         /**
-         * Returns whether to use the default text classifier to handle this request. This
-         * will be ignored if it is not the system text classifier to handle this request.
+         * Returns the information about the {@link SystemTextClassifier} that sent this request.
          *
          * @hide
          */
-        public boolean getUseDefaultTextClassifier() {
-            return mUseDefaultTextClassifier;
+        @Nullable
+        public SystemTextClassifierMetadata getSystemTextClassifierMetadata() {
+            return mSystemTcMetadata;
         }
 
         /**
@@ -585,30 +551,24 @@
             dest.writeString(mText.toString());
             dest.writeParcelable(mDefaultLocales, flags);
             dest.writeParcelable(mEntityConfig, flags);
-            dest.writeString(mCallingPackageName);
-            dest.writeInt(mUserId);
             dest.writeBundle(mExtras);
             dest.writeString(mReferenceTime == null ? null : mReferenceTime.toString());
-            dest.writeBoolean(mUseDefaultTextClassifier);
+            dest.writeParcelable(mSystemTcMetadata, flags);
         }
 
         private static Request readFromParcel(Parcel in) {
             final String text = in.readString();
             final LocaleList defaultLocales = in.readParcelable(null);
             final EntityConfig entityConfig = in.readParcelable(null);
-            final String callingPackageName = in.readString();
-            final int userId = in.readInt();
             final Bundle extras = in.readBundle();
             final String referenceTimeString = in.readString();
             final ZonedDateTime referenceTime = referenceTimeString == null
                     ? null : ZonedDateTime.parse(referenceTimeString);
-            final boolean useDefaultTextClassifier = in.readBoolean();
+            final SystemTextClassifierMetadata systemTcMetadata = in.readParcelable(null);
 
             final Request request = new Request(text, defaultLocales, entityConfig,
                     /* legacyFallback= */ true, referenceTime, extras);
-            request.setCallingPackageName(callingPackageName);
-            request.setUserId(userId);
-            request.setUseDefaultTextClassifier(useDefaultTextClassifier);
+            request.setSystemTextClassifierMetadata(systemTcMetadata);
             return request;
         }
 
diff --git a/core/java/android/view/textclassifier/TextSelection.java b/core/java/android/view/textclassifier/TextSelection.java
index 575a072..d8a632d 100644
--- a/core/java/android/view/textclassifier/TextSelection.java
+++ b/core/java/android/view/textclassifier/TextSelection.java
@@ -20,12 +20,10 @@
 import android.annotation.IntRange;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.annotation.UserIdInt;
 import android.os.Bundle;
 import android.os.LocaleList;
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.os.UserHandle;
 import android.text.SpannedString;
 import android.util.ArrayMap;
 import android.view.textclassifier.TextClassifier.EntityType;
@@ -213,10 +211,7 @@
         @Nullable private final LocaleList mDefaultLocales;
         private final boolean mDarkLaunchAllowed;
         private final Bundle mExtras;
-        @Nullable private String mCallingPackageName;
-        @UserIdInt
-        private int mUserId = UserHandle.USER_NULL;
-        private boolean mUseDefaultTextClassifier;
+        @Nullable private SystemTextClassifierMetadata mSystemTcMetadata;
 
         private Request(
                 CharSequence text,
@@ -278,62 +273,33 @@
         }
 
         /**
-         * Sets the name of the package that is sending this request.
-         * <p>
-         * Package-private for SystemTextClassifier's use.
-         * @hide
-         */
-        @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
-        public void setCallingPackageName(@Nullable String callingPackageName) {
-            mCallingPackageName = callingPackageName;
-        }
-
-        /**
          * Returns the name of the package that sent this request.
          * This returns {@code null} if no calling package name is set.
          */
         @Nullable
         public String getCallingPackageName() {
-            return mCallingPackageName;
+            return mSystemTcMetadata != null ? mSystemTcMetadata.getCallingPackageName() : null;
         }
 
         /**
-         * Sets the id of the user that sent this request.
-         * <p>
-         * Package-private for SystemTextClassifier's use.
-         * @hide
-         */
-        void setUserId(@UserIdInt int userId) {
-            mUserId = userId;
-        }
-
-        /**
-         * Returns the id of the user that sent this request.
-         * @hide
-         */
-        @UserIdInt
-        public int getUserId() {
-            return mUserId;
-        }
-
-        /**
-         * Sets whether to use the default text classifier to handle this request.
-         * This will be ignored if it is not the system text classifier to handle this request.
+         * Sets the information about the {@link SystemTextClassifier} that sent this request.
          *
          * @hide
          */
-        void setUseDefaultTextClassifier(boolean useDefaultTextClassifier) {
-            mUseDefaultTextClassifier = useDefaultTextClassifier;
+        @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
+        public void setSystemTextClassifierMetadata(
+                @Nullable SystemTextClassifierMetadata systemTcMetadata) {
+            mSystemTcMetadata = systemTcMetadata;
         }
 
         /**
-         * Returns whether to use the default text classifier to handle this request. This
-         * will be ignored if it is not the system text classifier to handle this request.
+         * Returns the information about the {@link SystemTextClassifier} that sent this request.
          *
          * @hide
          */
-        public boolean getUseDefaultTextClassifier() {
-            return mUseDefaultTextClassifier;
+        @Nullable
+        public SystemTextClassifierMetadata getSystemTextClassifierMetadata() {
+            return mSystemTcMetadata;
         }
 
         /**
@@ -438,10 +404,8 @@
             dest.writeInt(mStartIndex);
             dest.writeInt(mEndIndex);
             dest.writeParcelable(mDefaultLocales, flags);
-            dest.writeString(mCallingPackageName);
-            dest.writeInt(mUserId);
             dest.writeBundle(mExtras);
-            dest.writeBoolean(mUseDefaultTextClassifier);
+            dest.writeParcelable(mSystemTcMetadata, flags);
         }
 
         private static Request readFromParcel(Parcel in) {
@@ -449,16 +413,12 @@
             final int startIndex = in.readInt();
             final int endIndex = in.readInt();
             final LocaleList defaultLocales = in.readParcelable(null);
-            final String callingPackageName = in.readString();
-            final int userId = in.readInt();
             final Bundle extras = in.readBundle();
-            final boolean systemTextClassifierType = in.readBoolean();
+            final SystemTextClassifierMetadata systemTcMetadata = in.readParcelable(null);
 
             final Request request = new Request(text, startIndex, endIndex, defaultLocales,
                     /* darkLaunchAllowed= */ false, extras);
-            request.setCallingPackageName(callingPackageName);
-            request.setUserId(userId);
-            request.setUseDefaultTextClassifier(systemTextClassifierType);
+            request.setSystemTextClassifierMetadata(systemTcMetadata);
             return request;
         }
 
diff --git a/core/java/com/android/internal/view/inline/IInlineContentCallback.aidl b/core/java/com/android/internal/view/inline/IInlineContentCallback.aidl
index 29bdf56..feb3f02 100644
--- a/core/java/com/android/internal/view/inline/IInlineContentCallback.aidl
+++ b/core/java/com/android/internal/view/inline/IInlineContentCallback.aidl
@@ -24,4 +24,6 @@
  */
 oneway interface IInlineContentCallback {
     void onContent(in SurfaceControlViewHost.SurfacePackage content);
+    void onClick();
+    void onLongClick();
 }
diff --git a/core/tests/coretests/src/android/view/textclassifier/SystemTextClassifierMetadataTest.java b/core/tests/coretests/src/android/view/textclassifier/SystemTextClassifierMetadataTest.java
new file mode 100644
index 0000000..e4cfc53
--- /dev/null
+++ b/core/tests/coretests/src/android/view/textclassifier/SystemTextClassifierMetadataTest.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2020 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.view.textclassifier;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.testng.Assert.assertThrows;
+
+
+import android.os.Parcel;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class SystemTextClassifierMetadataTest {
+
+    @Test
+    public void testInvalidPackageNameThrowsException() {
+        assertThrows(NullPointerException.class,
+                () -> new SystemTextClassifierMetadata(/* packageName= */ null, /* userId= */
+                        1, /* useDefaultTextClassifier= */ false));
+    }
+
+    @Test
+    public void testParcel() {
+        SystemTextClassifierMetadata sysTcMetadata = new SystemTextClassifierMetadata(
+                "package", /* userId= */ 1, /* useDefaultTextClassifier= */ false);
+
+        Parcel p = Parcel.obtain();
+        sysTcMetadata.writeToParcel(p, 0);
+        p.setDataPosition(0);
+
+        SystemTextClassifierMetadata targetSysTcMetadata =
+                SystemTextClassifierMetadata.CREATOR.createFromParcel(p);
+
+        assertThat(targetSysTcMetadata.getUserId()).isEqualTo(sysTcMetadata.getUserId());
+        assertThat(targetSysTcMetadata.getCallingPackageName()).isEqualTo(
+                sysTcMetadata.getCallingPackageName());
+        assertThat(targetSysTcMetadata.useDefaultTextClassifier()).isEqualTo(
+                sysTcMetadata.useDefaultTextClassifier());
+    }
+}
diff --git a/core/tests/coretests/src/android/view/textclassifier/TextClassificationTest.java b/core/tests/coretests/src/android/view/textclassifier/TextClassificationTest.java
index d544029..39ededa 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TextClassificationTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TextClassificationTest.java
@@ -17,6 +17,7 @@
 package android.view.textclassifier;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 
@@ -199,7 +200,9 @@
                         .setReferenceTime(referenceTime)
                         .setExtras(BUNDLE)
                         .build();
-        reference.setCallingPackageName(packageName);
+        final SystemTextClassifierMetadata systemTcMetadata =
+                new SystemTextClassifierMetadata(packageName, 1, false);
+        reference.setSystemTextClassifierMetadata(systemTcMetadata);
 
         // Parcel and unparcel.
         final Parcel parcel = Parcel.obtain();
@@ -216,5 +219,11 @@
         assertEquals(referenceTime, result.getReferenceTime());
         assertEquals(BUNDLE_VALUE, result.getExtras().getString(BUNDLE_KEY));
         assertEquals(packageName, result.getCallingPackageName());
+        final SystemTextClassifierMetadata resultSystemTcMetadata =
+                result.getSystemTextClassifierMetadata();
+        assertNotNull(resultSystemTcMetadata);
+        assertEquals(packageName, resultSystemTcMetadata.getCallingPackageName());
+        assertEquals(1, resultSystemTcMetadata.getUserId());
+        assertFalse(resultSystemTcMetadata.useDefaultTextClassifier());
     }
 }
diff --git a/core/tests/coretests/src/android/view/textclassifier/TextLanguageTest.java b/core/tests/coretests/src/android/view/textclassifier/TextLanguageTest.java
index d0d32e3..31f8029 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TextLanguageTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TextLanguageTest.java
@@ -17,6 +17,8 @@
 package android.view.textclassifier;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
 
 import android.icu.util.ULocale;
 import android.os.Bundle;
@@ -75,7 +77,9 @@
         final TextLanguage.Request reference = new TextLanguage.Request.Builder(text)
                 .setExtras(bundle)
                 .build();
-        reference.setCallingPackageName(packageName);
+        final SystemTextClassifierMetadata systemTcMetadata =
+                new SystemTextClassifierMetadata(packageName, 1, false);
+        reference.setSystemTextClassifierMetadata(systemTcMetadata);
 
         final Parcel parcel = Parcel.obtain();
         reference.writeToParcel(parcel, 0);
@@ -85,5 +89,11 @@
         assertEquals(text, result.getText());
         assertEquals("bundle", result.getExtras().getString(bundleKey));
         assertEquals(packageName, result.getCallingPackageName());
+        final SystemTextClassifierMetadata resultSystemTcMetadata =
+                result.getSystemTextClassifierMetadata();
+        assertNotNull(resultSystemTcMetadata);
+        assertEquals(packageName, resultSystemTcMetadata.getCallingPackageName());
+        assertEquals(1, resultSystemTcMetadata.getUserId());
+        assertFalse(resultSystemTcMetadata.useDefaultTextClassifier());
     }
 }
diff --git a/core/tests/coretests/src/android/view/textclassifier/TextLinksTest.java b/core/tests/coretests/src/android/view/textclassifier/TextLinksTest.java
index ec5813f..4f0b44b 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TextLinksTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TextLinksTest.java
@@ -17,6 +17,8 @@
 package android.view.textclassifier;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
 
 import android.os.Bundle;
 import android.os.LocaleList;
@@ -115,7 +117,9 @@
                 .setExtras(BUNDLE)
                 .setReferenceTime(referenceTime)
                 .build();
-        reference.setCallingPackageName(packageName);
+        final SystemTextClassifierMetadata systemTcMetadata =
+                new SystemTextClassifierMetadata(packageName, 1, false);
+        reference.setSystemTextClassifierMetadata(systemTcMetadata);
 
         // Parcel and unparcel.
         final Parcel parcel = Parcel.obtain();
@@ -132,5 +136,11 @@
         assertEquals(BUNDLE_VALUE, result.getExtras().getString(BUNDLE_KEY));
         assertEquals(packageName, result.getCallingPackageName());
         assertEquals(referenceTime, result.getReferenceTime());
+        final SystemTextClassifierMetadata resultSystemTcMetadata =
+                result.getSystemTextClassifierMetadata();
+        assertNotNull(resultSystemTcMetadata);
+        assertEquals(packageName, resultSystemTcMetadata.getCallingPackageName());
+        assertEquals(1, resultSystemTcMetadata.getUserId());
+        assertFalse(resultSystemTcMetadata.useDefaultTextClassifier());
     }
 }
diff --git a/core/tests/coretests/src/android/view/textclassifier/TextSelectionTest.java b/core/tests/coretests/src/android/view/textclassifier/TextSelectionTest.java
index 30cc4e8..82788c8 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TextSelectionTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TextSelectionTest.java
@@ -17,6 +17,8 @@
 package android.view.textclassifier;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
 
 import android.os.Bundle;
 import android.os.LocaleList;
@@ -82,7 +84,9 @@
                         .setDefaultLocales(new LocaleList(Locale.US, Locale.GERMANY))
                         .setExtras(BUNDLE)
                         .build();
-        reference.setCallingPackageName(packageName);
+        final SystemTextClassifierMetadata systemTcMetadata =
+                new SystemTextClassifierMetadata(packageName, 1, false);
+        reference.setSystemTextClassifierMetadata(systemTcMetadata);
 
         // Parcel and unparcel.
         final Parcel parcel = Parcel.obtain();
@@ -96,5 +100,11 @@
         assertEquals("en-US,de-DE", result.getDefaultLocales().toLanguageTags());
         assertEquals(BUNDLE_VALUE, result.getExtras().getString(BUNDLE_KEY));
         assertEquals(packageName, result.getCallingPackageName());
+        final SystemTextClassifierMetadata resultSystemTcMetadata =
+                result.getSystemTextClassifierMetadata();
+        assertNotNull(resultSystemTcMetadata);
+        assertEquals(packageName, resultSystemTcMetadata.getCallingPackageName());
+        assertEquals(1, resultSystemTcMetadata.getUserId());
+        assertFalse(resultSystemTcMetadata.useDefaultTextClassifier());
     }
 }
diff --git a/packages/SystemUI/res/color/control_background.xml b/packages/SystemUI/res/color/control_background.xml
deleted file mode 100644
index 977310c..0000000
--- a/packages/SystemUI/res/color/control_background.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<selector xmlns:android="http://schemas.android.com/apk/res/android">
-  <item android:state_enabled="false"
-        android:color="@color/control_default_background" />
-  <item android:color="@color/GM2_blue_200"
-        android:alpha="0.2" />
-</selector>
diff --git a/packages/SystemUI/res/color/light_background.xml b/packages/SystemUI/res/color/light_background.xml
deleted file mode 100644
index 1299464..0000000
--- a/packages/SystemUI/res/color/light_background.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<selector xmlns:android="http://schemas.android.com/apk/res/android">
-  <item android:state_enabled="false"
-        android:color="@color/control_default_background" />
-  <item android:color="@color/GM2_yellow_200"
-        android:alpha="0.2" />
-</selector>
diff --git a/packages/SystemUI/res/color/thermo_cool_background.xml b/packages/SystemUI/res/color/thermo_cool_background.xml
deleted file mode 100644
index 977310c..0000000
--- a/packages/SystemUI/res/color/thermo_cool_background.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<selector xmlns:android="http://schemas.android.com/apk/res/android">
-  <item android:state_enabled="false"
-        android:color="@color/control_default_background" />
-  <item android:color="@color/GM2_blue_200"
-        android:alpha="0.2" />
-</selector>
diff --git a/packages/SystemUI/res/color/thermo_heat_background.xml b/packages/SystemUI/res/color/thermo_heat_background.xml
deleted file mode 100644
index 2709ebe..0000000
--- a/packages/SystemUI/res/color/thermo_heat_background.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<selector xmlns:android="http://schemas.android.com/apk/res/android">
-  <item android:state_enabled="false"
-        android:color="@color/control_default_background" />
-  <item android:color="@color/GM2_red_200"
-        android:alpha="0.2" />
-</selector>
diff --git a/packages/SystemUI/res/values/colors.xml b/packages/SystemUI/res/values/colors.xml
index 80c1ac8..56e2b06 100644
--- a/packages/SystemUI/res/values/colors.xml
+++ b/packages/SystemUI/res/values/colors.xml
@@ -225,4 +225,8 @@
     <color name="control_default_background">@color/GM2_grey_900</color>
     <color name="control_list_popup_background">@*android:color/background_floating_material_dark</color>
     <color name="control_spinner_dropdown">@*android:color/foreground_material_dark</color>
+    <color name="control_enabled_light_background">@color/GM2_yellow_200</color>
+    <color name="control_enabled_thermo_heat_background">@color/GM2_red_200</color>
+    <color name="control_enabled_thermo_cool_background">@color/GM2_blue_200</color>
+    <color name="control_enabled_default_background">@color/GM2_blue_200</color>
 </resources>
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt
index 23dc4c6..b439206 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt
@@ -17,8 +17,8 @@
 package com.android.systemui.controls.ui
 
 import android.content.Context
-import android.graphics.BlendMode
 import android.graphics.drawable.ClipDrawable
+import android.graphics.drawable.GradientDrawable
 import android.graphics.drawable.LayerDrawable
 import android.service.controls.Control
 import android.service.controls.actions.ControlAction
@@ -39,6 +39,8 @@
 import kotlin.reflect.KClass
 
 private const val UPDATE_DELAY_IN_MILLIS = 3000L
+private const val ALPHA_ENABLED = (255.0 * 0.2).toInt()
+private const val ALPHA_DISABLED = 255
 
 class ControlViewHolder(
     val layout: ViewGroup,
@@ -144,16 +146,21 @@
         val ri = RenderInfo.lookup(context, cws.componentName, deviceType, enabled, offset)
 
         val fg = context.getResources().getColorStateList(ri.foreground, context.getTheme())
-        val bg = context.getResources().getColorStateList(ri.background, context.getTheme())
+        val (bg, alpha) = if (enabled) {
+            Pair(ri.enabledBackground, ALPHA_ENABLED)
+        } else {
+            Pair(R.color.control_default_background, ALPHA_DISABLED)
+        }
+
         status.setTextColor(fg)
         statusExtra.setTextColor(fg)
 
         icon.setImageDrawable(ri.icon)
         icon.setImageTintList(fg)
 
-        clipLayer.getDrawable().apply {
-            setTintBlendMode(BlendMode.HUE)
-            setTintList(bg)
+        (clipLayer.getDrawable() as GradientDrawable).apply {
+            setColor(context.getResources().getColor(bg, context.getTheme()))
+            setAlpha(alpha)
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/RenderInfo.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/RenderInfo.kt
index 56267be..27e4649 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/RenderInfo.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/RenderInfo.kt
@@ -16,6 +16,7 @@
 
 package com.android.systemui.controls.ui
 
+import android.annotation.ColorRes
 import android.annotation.MainThread
 import android.content.ComponentName
 import android.content.Context
@@ -37,8 +38,11 @@
     }
 }
 
-data class RenderInfo(val icon: Drawable, val foreground: Int, val background: Int) {
-
+data class RenderInfo(
+    val icon: Drawable,
+    val foreground: Int,
+    @ColorRes val enabledBackground: Int
+) {
     companion object {
         const val APP_ICON_ID = -1
         private val iconMap = SparseArray<Drawable>()
@@ -72,6 +76,7 @@
                 icon = iconMap.get(resourceId)
                 if (icon == null) {
                     icon = context.resources.getDrawable(resourceId, null)
+                    icon.mutate()
                     iconMap.put(resourceId, icon)
                 }
             }
@@ -94,12 +99,13 @@
 
 private val deviceColorMap = mapOf<Int, Pair<Int, Int>>(
     (THERMOSTAT_RANGE + TemperatureControlTemplate.MODE_HEAT) to
-        Pair(R.color.thermo_heat_foreground, R.color.thermo_heat_background),
+        Pair(R.color.thermo_heat_foreground, R.color.control_enabled_thermo_heat_background),
     (THERMOSTAT_RANGE + TemperatureControlTemplate.MODE_COOL) to
-        Pair(R.color.thermo_cool_foreground, R.color.thermo_cool_background),
-    DeviceTypes.TYPE_LIGHT to Pair(R.color.light_foreground, R.color.light_background)
+        Pair(R.color.thermo_cool_foreground, R.color.control_enabled_thermo_cool_background),
+    DeviceTypes.TYPE_LIGHT
+        to Pair(R.color.light_foreground, R.color.control_enabled_light_background)
 ).withDefault {
-        Pair(R.color.control_foreground, R.color.control_background)
+        Pair(R.color.control_foreground, R.color.control_enabled_default_background)
 }
 
 private val deviceIconMap = mapOf<Int, IconState>(
diff --git a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java
index 27c81ce..59b28b4 100644
--- a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java
+++ b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java
@@ -99,7 +99,7 @@
 import com.android.systemui.plugins.ActivityStarter;
 import com.android.systemui.plugins.GlobalActions.GlobalActionsManager;
 import com.android.systemui.plugins.GlobalActionsPanelPlugin;
-import com.android.systemui.statusbar.BlurUtils;
+import com.android.systemui.statusbar.NotificationShadeDepthController;
 import com.android.systemui.statusbar.phone.NotificationShadeWindowController;
 import com.android.systemui.statusbar.phone.ScrimController;
 import com.android.systemui.statusbar.policy.ConfigurationController;
@@ -162,7 +162,7 @@
     private final IActivityManager mIActivityManager;
     private final TelecomManager mTelecomManager;
     private final MetricsLogger mMetricsLogger;
-    private final BlurUtils mBlurUtils;
+    private final NotificationShadeDepthController mDepthController;
 
     private ArrayList<Action> mItems;
     private ActionsDialog mDialog;
@@ -207,7 +207,7 @@
             KeyguardStateController keyguardStateController, UserManager userManager,
             TrustManager trustManager, IActivityManager iActivityManager,
             @Nullable TelecomManager telecomManager, MetricsLogger metricsLogger,
-            BlurUtils blurUtils, SysuiColorExtractor colorExtractor,
+            NotificationShadeDepthController depthController, SysuiColorExtractor colorExtractor,
             IStatusBarService statusBarService,
             NotificationShadeWindowController notificationShadeWindowController,
             ControlsUiController controlsUiController, IWindowManager iWindowManager,
@@ -229,7 +229,7 @@
         mIActivityManager = iActivityManager;
         mTelecomManager = telecomManager;
         mMetricsLogger = metricsLogger;
-        mBlurUtils = blurUtils;
+        mDepthController = depthController;
         mSysuiColorExtractor = colorExtractor;
         mStatusBarService = statusBarService;
         mNotificationShadeWindowController = notificationShadeWindowController;
@@ -437,7 +437,7 @@
                         : null;
 
         ActionsDialog dialog = new ActionsDialog(mContext, mAdapter, panelViewController,
-                mBlurUtils, mSysuiColorExtractor, mStatusBarService,
+                mDepthController, mSysuiColorExtractor, mStatusBarService,
                 mNotificationShadeWindowController,
                 shouldShowControls() ? mControlsUiController : null);
         dialog.setCanceledOnTouchOutside(false); // Handled by the custom class.
@@ -1570,20 +1570,21 @@
         private ResetOrientationData mResetOrientationData;
         private boolean mHadTopUi;
         private final NotificationShadeWindowController mNotificationShadeWindowController;
-        private final BlurUtils mBlurUtils;
+        private final NotificationShadeDepthController mDepthController;
 
         private ControlsUiController mControlsUiController;
         private ViewGroup mControlsView;
 
         ActionsDialog(Context context, MyAdapter adapter,
-                GlobalActionsPanelPlugin.PanelViewController plugin, BlurUtils blurUtils,
+                GlobalActionsPanelPlugin.PanelViewController plugin,
+                NotificationShadeDepthController depthController,
                 SysuiColorExtractor sysuiColorExtractor, IStatusBarService statusBarService,
                 NotificationShadeWindowController notificationShadeWindowController,
                 ControlsUiController controlsUiController) {
             super(context, com.android.systemui.R.style.Theme_SystemUI_Dialog_GlobalActions);
             mContext = context;
             mAdapter = adapter;
-            mBlurUtils = blurUtils;
+            mDepthController = depthController;
             mColorExtractor = sysuiColorExtractor;
             mStatusBarService = statusBarService;
             mNotificationShadeWindowController = notificationShadeWindowController;
@@ -1792,8 +1793,8 @@
                         float animatedValue = animation.getAnimatedFraction();
                         int alpha = (int) (animatedValue * mScrimAlpha * 255);
                         mBackgroundDrawable.setAlpha(alpha);
-                        mBlurUtils.applyBlur(mGlobalActionsLayout.getViewRootImpl(),
-                                mBlurUtils.blurRadiusOfRatio(animatedValue));
+                        mDepthController.updateGlobalDialogVisibility(animatedValue,
+                                mGlobalActionsLayout);
                     })
                     .start();
             if (mControlsUiController != null) {
@@ -1822,8 +1823,8 @@
                         float animatedValue = 1f - animation.getAnimatedFraction();
                         int alpha = (int) (animatedValue * mScrimAlpha * 255);
                         mBackgroundDrawable.setAlpha(alpha);
-                        mBlurUtils.applyBlur(mGlobalActionsLayout.getViewRootImpl(),
-                                mBlurUtils.blurRadiusOfRatio(animatedValue));
+                        mDepthController.updateGlobalDialogVisibility(animatedValue,
+                                mGlobalActionsLayout);
                     })
                     .start();
             dismissPanel();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt
index 901ed3f..eb8526d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt
@@ -58,6 +58,7 @@
     }
 
     lateinit var root: View
+    private var blurRoot: View? = null
     private var keyguardAnimator: Animator? = null
     private var notificationAnimator: Animator? = null
     private var updateScheduled: Boolean = false
@@ -72,6 +73,7 @@
             return shadeBlurRadius.toFloat()
         }
     })
+    private val zoomInterpolator = Interpolators.ACCELERATE_DECELERATE
     private var shadeBlurRadius = 0
         set(value) {
             if (field == value) return
@@ -84,6 +86,7 @@
             field = value
             scheduleUpdate()
         }
+    private var globalDialogVisibility = 0f
 
     /**
      * Callback that updates the window blur value and is called only once per frame.
@@ -91,9 +94,12 @@
     private val updateBlurCallback = Choreographer.FrameCallback {
         updateScheduled = false
 
-        val blur = max(shadeBlurRadius, wakeAndUnlockBlurRadius)
-        blurUtils.applyBlur(root.viewRootImpl, blur)
-        wallpaperManager.setWallpaperZoomOut(root.windowToken, blurUtils.ratioOfBlurRadius(blur))
+        val blur = max(shadeBlurRadius,
+                max(wakeAndUnlockBlurRadius, blurUtils.blurRadiusOfRatio(globalDialogVisibility)))
+        blurUtils.applyBlur(blurRoot?.viewRootImpl ?: root.viewRootImpl, blur)
+        val rawZoom = max(blurUtils.ratioOfBlurRadius(blur), globalDialogVisibility)
+        wallpaperManager.setWallpaperZoomOut(root.windowToken,
+                zoomInterpolator.getInterpolation(rawZoom))
     }
 
     /**
@@ -162,14 +168,23 @@
         shadeSpring.animateToFinalPosition(newBlur.toFloat())
     }
 
-    private fun scheduleUpdate() {
+    private fun scheduleUpdate(viewToBlur: View? = null) {
         if (updateScheduled) {
             return
         }
         updateScheduled = true
+        blurRoot = viewToBlur
         choreographer.postFrameCallback(updateBlurCallback)
     }
 
+    fun updateGlobalDialogVisibility(visibility: Float, dialogView: View) {
+        if (visibility == globalDialogVisibility) {
+            return
+        }
+        globalDialogVisibility = visibility
+        scheduleUpdate(dialogView)
+    }
+
     override fun dump(fd: FileDescriptor, pw: PrintWriter, args: Array<out String>) {
         IndentingPrintWriter(pw, "  ").let {
             it.println("StatusBarWindowBlurController:")
diff --git a/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java b/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java
index e73f9ce..53afa6e 100644
--- a/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java
+++ b/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java
@@ -57,6 +57,7 @@
 import com.android.internal.os.IResultReceiver;
 import com.android.server.autofill.ui.InlineSuggestionFactory;
 
+import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.CancellationException;
 import java.util.concurrent.TimeUnit;
@@ -255,8 +256,12 @@
                             mCallbacks.logAugmentedAutofillSelected(sessionId,
                                     dataset.getId());
                             try {
-                                client.autofill(sessionId, dataset.getFieldIds(),
-                                        dataset.getFieldValues());
+                                final ArrayList<AutofillId> fieldIds = dataset.getFieldIds();
+                                final int size = fieldIds.size();
+                                final boolean hideHighlight = size == 1
+                                        && fieldIds.get(0).equals(focusedId);
+                                client.autofill(sessionId, fieldIds, dataset.getFieldValues(),
+                                        hideHighlight);
                             } catch (RemoteException e) {
                                 Slog.w(TAG, "Encounter exception autofilling the values");
                             }
diff --git a/services/autofill/java/com/android/server/autofill/Session.java b/services/autofill/java/com/android/server/autofill/Session.java
index 8265009..9693535 100644
--- a/services/autofill/java/com/android/server/autofill/Session.java
+++ b/services/autofill/java/com/android/server/autofill/Session.java
@@ -3382,6 +3382,8 @@
                 final List<AutofillId> ids = new ArrayList<>(entryCount);
                 final List<AutofillValue> values = new ArrayList<>(entryCount);
                 boolean waitingDatasetAuth = false;
+                boolean hideHighlight = (entryCount == 1
+                        && dataset.getFieldIds().get(0).equals(mCurrentViewId));
                 for (int i = 0; i < entryCount; i++) {
                     if (dataset.getFieldValues().get(i) == null) {
                         continue;
@@ -3405,7 +3407,7 @@
                     }
                     if (sDebug) Slog.d(TAG, "autoFillApp(): the buck is on the app: " + dataset);
 
-                    mClient.autofill(id, ids, values);
+                    mClient.autofill(id, ids, values, hideHighlight);
                     if (dataset.getId() != null) {
                         if (mSelectedDatasetIds == null) {
                             mSelectedDatasetIds = new ArrayList<>();
diff --git a/services/autofill/java/com/android/server/autofill/ui/InlineSuggestionFactory.java b/services/autofill/java/com/android/server/autofill/ui/InlineSuggestionFactory.java
index ee59d89..0ca9dd9 100644
--- a/services/autofill/java/com/android/server/autofill/ui/InlineSuggestionFactory.java
+++ b/services/autofill/java/com/android/server/autofill/ui/InlineSuggestionFactory.java
@@ -329,8 +329,14 @@
             @NonNull Runnable onErrorCallback) {
         return new IInlineSuggestionUiCallback.Stub() {
             @Override
-            public void onAutofill() throws RemoteException {
+            public void onClick() throws RemoteException {
                 onAutofillCallback.run();
+                callback.onClick();
+            }
+
+            @Override
+            public void onLongClick() throws RemoteException {
+                callback.onLongClick();
             }
 
             @Override
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index 7287a44..ecf1f13 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -7803,12 +7803,15 @@
     private void handleNetworkTestedWithExtras(
             @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
         final NetworkAgentInfo nai = reportEvent.mNai;
+        final NetworkCapabilities networkCapabilities =
+                new NetworkCapabilities(nai.networkCapabilities);
+        clearNetworkCapabilitiesUids(networkCapabilities);
         final ConnectivityReport report =
                 new ConnectivityReport(
                         reportEvent.mNai.network,
                         reportEvent.mTimestampMillis,
                         nai.linkProperties,
-                        nai.networkCapabilities,
+                        networkCapabilities,
                         extras);
         final List<IConnectivityDiagnosticsCallback> results =
                 getMatchingPermissionedCallbacks(nai);
@@ -7824,13 +7827,16 @@
     private void handleDataStallSuspected(
             @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
             @NonNull PersistableBundle extras) {
+        final NetworkCapabilities networkCapabilities =
+                new NetworkCapabilities(nai.networkCapabilities);
+        clearNetworkCapabilitiesUids(networkCapabilities);
         final DataStallReport report =
                 new DataStallReport(
                         nai.network,
                         timestampMillis,
                         detectionMethod,
                         nai.linkProperties,
-                        nai.networkCapabilities,
+                        networkCapabilities,
                         extras);
         final List<IConnectivityDiagnosticsCallback> results =
                 getMatchingPermissionedCallbacks(nai);
@@ -7856,6 +7862,12 @@
         }
     }
 
+    private void clearNetworkCapabilitiesUids(@NonNull NetworkCapabilities nc) {
+        nc.setUids(null);
+        nc.setAdministratorUids(Collections.EMPTY_LIST);
+        nc.setOwnerUid(Process.INVALID_UID);
+    }
+
     private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
             @NonNull NetworkAgentInfo nai) {
         final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
diff --git a/services/core/java/com/android/server/connectivity/Vpn.java b/services/core/java/com/android/server/connectivity/Vpn.java
index 7c3cab1..20ffd9f 100644
--- a/services/core/java/com/android/server/connectivity/Vpn.java
+++ b/services/core/java/com/android/server/connectivity/Vpn.java
@@ -2563,7 +2563,7 @@
         public void exitIfOuterInterfaceIs(String interfaze) {
             if (interfaze.equals(mOuterInterface)) {
                 Log.i(TAG, "Legacy VPN is going down with " + interfaze);
-                exit();
+                exitVpnRunner();
             }
         }
 
@@ -2572,6 +2572,10 @@
         public void exitVpnRunner() {
             // We assume that everything is reset after stopping the daemons.
             interrupt();
+
+            // Always disconnect. This may be called again in cleanupVpnStateLocked() if
+            // exitVpnRunner() was called from exit(), but it will be a no-op.
+            agentDisconnect();
             try {
                 mContext.unregisterReceiver(mBroadcastReceiver);
             } catch (IllegalArgumentException e) {}
@@ -2794,7 +2798,7 @@
             } catch (Exception e) {
                 Log.i(TAG, "Aborting", e);
                 updateState(DetailedState.FAILED, e.getMessage());
-                exit();
+                exitVpnRunner();
             }
         }
 
diff --git a/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java b/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java
index 8164526..74a6383 100644
--- a/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java
+++ b/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java
@@ -41,6 +41,7 @@
 import android.util.SparseArray;
 import android.view.textclassifier.ConversationActions;
 import android.view.textclassifier.SelectionEvent;
+import android.view.textclassifier.SystemTextClassifierMetadata;
 import android.view.textclassifier.TextClassification;
 import android.view.textclassifier.TextClassificationConstants;
 import android.view.textclassifier.TextClassificationContext;
@@ -179,12 +180,12 @@
             TextSelection.Request request, ITextClassifierCallback callback)
             throws RemoteException {
         Objects.requireNonNull(request);
+        Objects.requireNonNull(request.getSystemTextClassifierMetadata());
 
         handleRequest(
-                request.getUserId(),
-                request.getCallingPackageName(),
+                request.getSystemTextClassifierMetadata(),
+                /* verifyCallingPackage= */ true,
                 /* attemptToBind= */ true,
-                request.getUseDefaultTextClassifier(),
                 service -> service.onSuggestSelection(sessionId, request, callback),
                 "onSuggestSelection",
                 callback);
@@ -196,12 +197,12 @@
             TextClassification.Request request, ITextClassifierCallback callback)
             throws RemoteException {
         Objects.requireNonNull(request);
+        Objects.requireNonNull(request.getSystemTextClassifierMetadata());
 
         handleRequest(
-                request.getUserId(),
-                request.getCallingPackageName(),
+                request.getSystemTextClassifierMetadata(),
+                /* verifyCallingPackage= */ true,
                 /* attemptToBind= */ true,
-                request.getUseDefaultTextClassifier(),
                 service -> service.onClassifyText(sessionId, request, callback),
                 "onClassifyText",
                 callback);
@@ -213,12 +214,12 @@
             TextLinks.Request request, ITextClassifierCallback callback)
             throws RemoteException {
         Objects.requireNonNull(request);
+        Objects.requireNonNull(request.getSystemTextClassifierMetadata());
 
         handleRequest(
-                request.getUserId(),
-                request.getCallingPackageName(),
+                request.getSystemTextClassifierMetadata(),
+                /* verifyCallingPackage= */ true,
                 /* attemptToBind= */ true,
-                request.getUseDefaultTextClassifier(),
                 service -> service.onGenerateLinks(sessionId, request, callback),
                 "onGenerateLinks",
                 callback);
@@ -229,12 +230,12 @@
             @Nullable TextClassificationSessionId sessionId, SelectionEvent event)
             throws RemoteException {
         Objects.requireNonNull(event);
+        Objects.requireNonNull(event.getSystemTextClassifierMetadata());
 
         handleRequest(
-                event.getUserId(),
-                /* callingPackageName= */ null,
+                event.getSystemTextClassifierMetadata(),
+                /* verifyCallingPackage= */ false,
                 /* attemptToBind= */ false,
-                event.getUseDefaultTextClassifier(),
                 service -> service.onSelectionEvent(sessionId, event),
                 "onSelectionEvent",
                 NO_OP_CALLBACK);
@@ -246,18 +247,14 @@
             TextClassifierEvent event) throws RemoteException {
         Objects.requireNonNull(event);
 
-        final int userId = event.getEventContext() == null
-                ? UserHandle.getCallingUserId()
-                : event.getEventContext().getUserId();
-        final boolean useDefaultTextClassifier =
-                event.getEventContext() != null
-                        ? event.getEventContext().getUseDefaultTextClassifier()
-                        : true;
+        final TextClassificationContext eventContext = event.getEventContext();
+        final SystemTextClassifierMetadata systemTcMetadata =
+                eventContext != null ? eventContext.getSystemTextClassifierMetadata() : null;
+
         handleRequest(
-                userId,
-                /* callingPackageName= */ null,
+                systemTcMetadata,
+                /* verifyCallingPackage= */ false,
                 /* attemptToBind= */ false,
-                useDefaultTextClassifier,
                 service -> service.onTextClassifierEvent(sessionId, event),
                 "onTextClassifierEvent",
                 NO_OP_CALLBACK);
@@ -269,12 +266,12 @@
             TextLanguage.Request request,
             ITextClassifierCallback callback) throws RemoteException {
         Objects.requireNonNull(request);
+        Objects.requireNonNull(request.getSystemTextClassifierMetadata());
 
         handleRequest(
-                request.getUserId(),
-                request.getCallingPackageName(),
+                request.getSystemTextClassifierMetadata(),
+                /* verifyCallingPackage= */ true,
                 /* attemptToBind= */ true,
-                request.getUseDefaultTextClassifier(),
                 service -> service.onDetectLanguage(sessionId, request, callback),
                 "onDetectLanguage",
                 callback);
@@ -286,12 +283,12 @@
             ConversationActions.Request request,
             ITextClassifierCallback callback) throws RemoteException {
         Objects.requireNonNull(request);
+        Objects.requireNonNull(request.getSystemTextClassifierMetadata());
 
         handleRequest(
-                request.getUserId(),
-                request.getCallingPackageName(),
+                request.getSystemTextClassifierMetadata(),
+                /* verifyCallingPackage= */ true,
                 /* attemptToBind= */ true,
-                request.getUseDefaultTextClassifier(),
                 service -> service.onSuggestConversationActions(sessionId, request, callback),
                 "onSuggestConversationActions",
                 callback);
@@ -303,13 +300,12 @@
             throws RemoteException {
         Objects.requireNonNull(sessionId);
         Objects.requireNonNull(classificationContext);
+        Objects.requireNonNull(classificationContext.getSystemTextClassifierMetadata());
 
-        final int userId = classificationContext.getUserId();
         handleRequest(
-                userId,
-                classificationContext.getPackageName(),
+                classificationContext.getSystemTextClassifierMetadata(),
+                /* verifyCallingPackage= */ true,
                 /* attemptToBind= */ false,
-                classificationContext.getUseDefaultTextClassifier(),
                 service -> {
                     service.onCreateTextClassificationSession(classificationContext, sessionId);
                     mSessionCache.put(sessionId, classificationContext);
@@ -333,11 +329,13 @@
                     textClassificationContext != null
                             ? textClassificationContext.useDefaultTextClassifier
                             : true;
+            final SystemTextClassifierMetadata sysTcMetadata = new SystemTextClassifierMetadata(
+                    "", userId, useDefaultTextClassifier);
+
             handleRequest(
-                    userId,
-                    /* callingPackageName= */ null,
+                    sysTcMetadata,
+                    /* verifyCallingPackage= */ false,
                     /* attemptToBind= */ false,
-                    useDefaultTextClassifier,
                     service -> {
                         service.onDestroyTextClassificationSession(sessionId);
                         mSessionCache.remove(sessionId);
@@ -412,10 +410,9 @@
     }
 
     private void handleRequest(
-            @UserIdInt int userId,
-            @Nullable String callingPackageName,
+            @Nullable SystemTextClassifierMetadata sysTcMetadata,
+            boolean verifyCallingPackage,
             boolean attemptToBind,
-            boolean useDefaultTextClassifier,
             @NonNull ThrowingConsumer<ITextClassifierService> textClassifierServiceConsumer,
             @NonNull String methodName,
             @NonNull ITextClassifierCallback callback) throws RemoteException {
@@ -423,8 +420,17 @@
         Objects.requireNonNull(methodName);
         Objects.requireNonNull(callback);
 
+        final int userId =
+                sysTcMetadata == null ? UserHandle.getCallingUserId() : sysTcMetadata.getUserId();
+        final String callingPackageName =
+                sysTcMetadata == null ? null : sysTcMetadata.getCallingPackageName();
+        final boolean useDefaultTextClassifier =
+                sysTcMetadata == null ? true : sysTcMetadata.useDefaultTextClassifier();
+
         try {
-            validateCallingPackage(callingPackageName);
+            if (verifyCallingPackage) {
+                validateCallingPackage(callingPackageName);
+            }
             validateUser(userId);
         } catch (Exception e) {
             throw new RemoteException("Invalid request: " + e.getMessage(), e,
@@ -636,8 +642,10 @@
         public final boolean useDefaultTextClassifier;
 
         StrippedTextClassificationContext(TextClassificationContext textClassificationContext) {
-            userId = textClassificationContext.getUserId();
-            useDefaultTextClassifier = textClassificationContext.getUseDefaultTextClassifier();
+            SystemTextClassifierMetadata sysTcMetadata =
+                    textClassificationContext.getSystemTextClassifierMetadata();
+            userId = sysTcMetadata.getUserId();
+            useDefaultTextClassifier = sysTcMetadata.useDefaultTextClassifier();
         }
     }
 
diff --git a/services/core/java/com/android/server/tv/UinputBridge.java b/services/core/java/com/android/server/tv/UinputBridge.java
index 752aa66..a2fe5fc 100644
--- a/services/core/java/com/android/server/tv/UinputBridge.java
+++ b/services/core/java/com/android/server/tv/UinputBridge.java
@@ -28,7 +28,7 @@
 public final class UinputBridge {
     private final CloseGuard mCloseGuard = CloseGuard.get();
     private long mPtr;
-    private IBinder mToken = null;
+    private IBinder mToken;
 
     private static native long nativeOpen(String name, String uniqueId, int width, int height,
                                           int maxPointers);
@@ -39,6 +39,25 @@
     private static native void nativeSendPointerUp(long ptr, int pointerId);
     private static native void nativeSendPointerSync(long ptr);
 
+    /** Opens a gamepad - will support gamepad key and axis sending */
+    private static native long nativeGamepadOpen(String name, String uniqueId);
+
+    /** Marks the specified key up/down for a gamepad */
+    private static native void nativeSendGamepadKey(long ptr, int keyIndex, boolean down);
+
+    /**
+     * Gamepads pre-define the following axes:
+     *   - Left joystick X, axis == ABS_X == 0, range [0, 254]
+     *   - Left joystick Y, axis == ABS_Y == 1, range [0, 254]
+     *   - Right joystick X, axis == ABS_RX == 3, range [0, 254]
+     *   - Right joystick Y, axis == ABS_RY == 4, range [0, 254]
+     *   - Left trigger, axis == ABS_Z == 2, range [0, 254]
+     *   - Right trigger, axis == ABS_RZ == 5, range [0, 254]
+     *   - DPad X, axis == ABS_HAT0X == 0x10, range [-1, 1]
+     *   - DPad Y, axis == ABS_HAT0Y == 0x11, range [-1, 1]
+     */
+    private static native void nativeSendGamepadAxisValue(long ptr, int axis, int value);
+
     public UinputBridge(IBinder token, String name, int width, int height, int maxPointers)
                         throws IOException {
         if (width < 1 || height < 1) {
@@ -58,12 +77,31 @@
         mCloseGuard.open("close");
     }
 
+    /** Constructor used by static factory methods */
+    private UinputBridge(IBinder token, long ptr) {
+        mPtr = ptr;
+        mToken = token;
+        mCloseGuard.open("close");
+    }
+
+    /** Opens a UinputBridge that supports gamepad buttons and axes. */
+    public static UinputBridge openGamepad(IBinder token, String name)
+            throws IOException {
+        if (token == null) {
+            throw new IllegalArgumentException("Token cannot be null");
+        }
+        long ptr = nativeGamepadOpen(name, token.toString());
+        if (ptr == 0) {
+            throw new IOException("Could not open uinput device " + name);
+        }
+
+        return new UinputBridge(token, ptr);
+    }
+
     @Override
     protected void finalize() throws Throwable {
         try {
-            if (mCloseGuard != null) {
-                mCloseGuard.warnIfOpen();
-            }
+            mCloseGuard.warnIfOpen();
             close(mToken);
         } finally {
             mToken = null;
@@ -119,7 +157,35 @@
         if (isTokenValid(token)) {
             nativeSendPointerSync(mPtr);
         }
+    }
 
+    /** Send a gamepad key
+     *  @param keyIndex - the index of the w3-spec key
+     *  @param down - is the key pressed ?
+     */
+    public void sendGamepadKey(IBinder token, int keyIndex, boolean down) {
+        if (isTokenValid(token)) {
+            nativeSendGamepadKey(mPtr, keyIndex, down);
+        }
+    }
+
+    /** Send a gamepad axis value.
+     *   - Left joystick X, axis == ABS_X == 0, range [0, 254]
+     *   - Left joystick Y, axis == ABS_Y == 1, range [0, 254]
+     *   - Right joystick X, axis == ABS_RX == 3, range [0, 254]
+     *   - Right joystick Y, axis == ABS_RY == 4, range [0, 254]
+     *   - Left trigger, axis == ABS_Z == 2, range [0, 254]
+     *   - Right trigger, axis == ABS_RZ == 5, range [0, 254]
+     *   - DPad X, axis == ABS_HAT0X == 0x10, range [-1, 1]
+     *   - DPad Y, axis == ABS_HAT0Y == 0x11, range [-1, 1]
+     *
+     * @param axis is the axis index
+     * @param value is the value to set for that axis
+     */
+    public void sendGamepadAxisValue(IBinder token, int axis, int value) {
+        if (isTokenValid(token)) {
+            nativeSendGamepadAxisValue(mPtr, axis, value);
+        }
     }
 
     public void clear(IBinder token) {
diff --git a/services/core/jni/com_android_server_tv_GamepadKeys.h b/services/core/jni/com_android_server_tv_GamepadKeys.h
new file mode 100644
index 0000000..11fc903
--- /dev/null
+++ b/services/core/jni/com_android_server_tv_GamepadKeys.h
@@ -0,0 +1,79 @@
+#ifndef ANDROIDTVREMOTE_SERVICE_JNI_GAMEPAD_KEYS_H_
+#define ANDROIDTVREMOTE_SERVICE_JNI_GAMEPAD_KEYS_H_
+
+#include <linux/input.h>
+
+namespace android {
+
+// Follows the W3 spec for gamepad buttons and their corresponding mapping into
+// Linux keycodes. Note that gamepads are generally not very well standardized
+// and various controllers will result in different buttons. This mapping tries
+// to be reasonable.
+//
+// W3 Button spec: https://www.w3.org/TR/gamepad/#remapping
+//
+// Standard gamepad keycodes are added plus 2 additional buttons (e.g. Stadia
+// has "Assistant" and "Share", PS4 has the touchpad button).
+//
+// To generate this list, PS4, XBox, Stadia and Nintendo Switch Pro were tested.
+static const int GAMEPAD_KEY_CODES[19] = {
+        // Right-side buttons. A/B/X/Y or circle/triangle/square/X or similar
+        BTN_A, // "South", A, GAMEPAD and SOUTH have the same constant
+        BTN_B, // "East", BTN_B, BTN_EAST have the same constant
+        BTN_X, // "West", Note that this maps to X and NORTH in constants
+        BTN_Y, // "North", Note that this maps to Y and WEST in constants
+
+        BTN_TL, // "Left Bumper" / "L1" - Nintendo sends BTN_WEST instead
+        BTN_TR, // "Right Bumper" / "R1" - Nintendo sends BTN_Z instead
+
+        // For triggers, gamepads vary:
+        //   - Stadia sends analog values over ABS_GAS/ABS_BRAKE and sends
+        //     TriggerHappy3/4 as digital presses
+        //   - PS4 and Xbox send analog values as ABS_Z/ABS_RZ
+        //   - Nintendo Pro sends BTN_TL/BTN_TR (since bumpers behave differently)
+        // As placeholders we chose the stadia trigger-happy values since TL/TR are
+        // sent for bumper button presses
+        BTN_TRIGGER_HAPPY4, // "Left Trigger" / "L2"
+        BTN_TRIGGER_HAPPY3, // "Right Trigger" / "R2"
+
+        BTN_SELECT, // "Select/Back". Often "options" or similar
+        BTN_START,  // "Start/forward". Often "hamburger" icon
+
+        BTN_THUMBL, // "Left Joystick Pressed"
+        BTN_THUMBR, // "Right Joystick Pressed"
+
+        // For DPads, gamepads generally only send axis changes
+        // on ABS_HAT0X and ABS_HAT0Y.
+        KEY_UP,    // "Digital Pad up"
+        KEY_DOWN,  // "Digital Pad down"
+        KEY_LEFT,  // "Digital Pad left"
+        KEY_RIGHT, // "Digital Pad right"
+
+        BTN_MODE, // "Main button" (Stadia/PS/XBOX/Home)
+
+        BTN_TRIGGER_HAPPY1, // Extra button: "Assistant" for Stadia
+        BTN_TRIGGER_HAPPY2, // Extra button: "Share" for Stadia
+};
+
+// Defines information for an axis.
+struct Axis {
+    int number;
+    int rangeMin;
+    int rangeMax;
+};
+
+// List of all axes supported by a gamepad
+static const Axis GAMEPAD_AXES[] = {
+        {ABS_X, 0, 254},    // Left joystick X
+        {ABS_Y, 0, 254},    // Left joystick Y
+        {ABS_RX, 0, 254},   // Right joystick X
+        {ABS_RY, 0, 254},   // Right joystick Y
+        {ABS_Z, 0, 254},    // Left trigger
+        {ABS_RZ, 0, 254},   // Right trigger
+        {ABS_HAT0X, -1, 1}, // DPad X
+        {ABS_HAT0Y, -1, 1}, // DPad Y
+};
+
+} // namespace android
+
+#endif // ANDROIDTVREMOTE_SERVICE_JNI_GAMEPAD_KEYS_H_
diff --git a/services/core/jni/com_android_server_tv_TvKeys.h b/services/core/jni/com_android_server_tv_TvKeys.h
index 4895f34..7eacdf6 100644
--- a/services/core/jni/com_android_server_tv_TvKeys.h
+++ b/services/core/jni/com_android_server_tv_TvKeys.h
@@ -110,4 +110,4 @@
 
 } // namespace android
 
-#endif // SERVICE_JNI_KEYS_H_
+#endif // ANDROIDTVREMOTE_SERVICE_JNI_KEYS_H_
diff --git a/services/core/jni/com_android_server_tv_TvUinputBridge.cpp b/services/core/jni/com_android_server_tv_TvUinputBridge.cpp
index c832c18..0e96bd7 100644
--- a/services/core/jni/com_android_server_tv_TvUinputBridge.cpp
+++ b/services/core/jni/com_android_server_tv_TvUinputBridge.cpp
@@ -16,6 +16,7 @@
 
 #define LOG_TAG "TvRemote-native-uiBridge"
 
+#include "com_android_server_tv_GamepadKeys.h"
 #include "com_android_server_tv_TvKeys.h"
 
 #include "jni.h"
@@ -92,27 +93,156 @@
     }
 }
 
+static const int kInvalidFileDescriptor = -1;
+
+// Convenience class to manage an opened /dev/uinput device
+class UInputDescriptor {
+public:
+    UInputDescriptor() : mFd(kInvalidFileDescriptor) {
+        memset(&mUinputDescriptor, 0, sizeof(mUinputDescriptor));
+    }
+
+    // Auto-closes any open /dev/uinput descriptor unless detached.
+    ~UInputDescriptor();
+
+    // Open /dev/uinput and prepare to register
+    // the device with the given name and unique Id
+    bool Open(const char* name, const char* uniqueId);
+
+    // Checks if the current file descriptor is valid
+    bool IsValid() const { return mFd != kInvalidFileDescriptor; }
+
+    void EnableKey(int keyCode);
+
+    void EnableAxesEvents();
+    void EnableAxis(int axis, int rangeMin, int rangeMax);
+
+    bool Create();
+
+    // Detaches from the current file descriptor
+    // Returns the file descriptor for /dev/uniput
+    int Detach();
+
+private:
+    int mFd;
+    struct uinput_user_dev mUinputDescriptor;
+};
+
+UInputDescriptor::~UInputDescriptor() {
+    if (mFd != kInvalidFileDescriptor) {
+        close(mFd);
+        mFd = kInvalidFileDescriptor;
+    }
+}
+
+int UInputDescriptor::Detach() {
+    int fd = mFd;
+    mFd = kInvalidFileDescriptor;
+    return fd;
+}
+
+bool UInputDescriptor::Open(const char* name, const char* uniqueId) {
+    if (IsValid()) {
+        ALOGE("UInput device already open");
+        return false;
+    }
+
+    mFd = ::open("/dev/uinput", O_WRONLY | O_NDELAY);
+    if (mFd < 0) {
+        ALOGE("Cannot open /dev/uinput: %s.", strerror(errno));
+        mFd = kInvalidFileDescriptor;
+        return false;
+    }
+
+    // write device unique id to the phys property
+    ioctl(mFd, UI_SET_PHYS, uniqueId);
+
+    memset(&mUinputDescriptor, 0, sizeof(mUinputDescriptor));
+    strlcpy(mUinputDescriptor.name, name, UINPUT_MAX_NAME_SIZE);
+    mUinputDescriptor.id.version = 1;
+    mUinputDescriptor.id.bustype = BUS_VIRTUAL;
+
+    // All UInput devices we use process keys
+    ioctl(mFd, UI_SET_EVBIT, EV_KEY);
+
+    return true;
+}
+
+void UInputDescriptor::EnableKey(int keyCode) {
+    ioctl(mFd, UI_SET_KEYBIT, keyCode);
+}
+
+void UInputDescriptor::EnableAxesEvents() {
+    ioctl(mFd, UI_SET_EVBIT, EV_ABS);
+}
+
+void UInputDescriptor::EnableAxis(int axis, int rangeMin, int rangeMax) {
+    if ((axis < 0) || (axis >= NELEM(mUinputDescriptor.absmin))) {
+        ALOGE("Invalid axis number: %d", axis);
+        return;
+    }
+
+    if (ioctl(mFd, UI_SET_ABSBIT, axis) != 0) {
+        ALOGE("Failed to set absbit for %d", axis);
+    }
+
+    mUinputDescriptor.absmin[axis] = rangeMin;
+    mUinputDescriptor.absmax[axis] = rangeMax;
+    mUinputDescriptor.absfuzz[axis] = 0;
+    mUinputDescriptor.absflat[axis] = 0;
+}
+
+bool UInputDescriptor::Create() {
+    // register the input device
+    if (write(mFd, &mUinputDescriptor, sizeof(mUinputDescriptor)) != sizeof(mUinputDescriptor)) {
+        ALOGE("Cannot write uinput_user_dev to fd %d: %s.", mFd, strerror(errno));
+        return false;
+    }
+
+    if (ioctl(mFd, UI_DEV_CREATE) != 0) {
+        ALOGE("Unable to create uinput device: %s.", strerror(errno));
+        return false;
+    }
+
+    ALOGV("Created uinput device, fd=%d.", mFd);
+
+    return true;
+}
+
 class NativeConnection {
 public:
+    enum class ConnectionType {
+        kRemoteDevice,
+        kGamepadDevice,
+    };
+
     ~NativeConnection();
 
     static NativeConnection* open(const char* name, const char* uniqueId,
             int32_t width, int32_t height, int32_t maxPointerId);
 
+    static NativeConnection* openGamepad(const char* name, const char* uniqueId);
+
     void sendEvent(int32_t type, int32_t code, int32_t value);
 
     int32_t getMaxPointers() const { return mMaxPointers; }
 
+    ConnectionType getType() const { return mType; }
+
+    bool IsGamepad() const { return getType() == ConnectionType::kGamepadDevice; }
+
+    bool IsRemote() const { return getType() == ConnectionType::kRemoteDevice; }
+
 private:
-    NativeConnection(int fd, int32_t maxPointers);
+    NativeConnection(int fd, int32_t maxPointers, ConnectionType type);
 
     const int mFd;
     const int32_t mMaxPointers;
+    const ConnectionType mType;
 };
 
-NativeConnection::NativeConnection(int fd, int32_t maxPointers) :
-        mFd(fd), mMaxPointers(maxPointers) {
-}
+NativeConnection::NativeConnection(int fd, int32_t maxPointers, ConnectionType type)
+      : mFd(fd), mMaxPointers(maxPointers), mType(type) {}
 
 NativeConnection::~NativeConnection() {
     ALOGI("Un-Registering uinput device %d.", mFd);
@@ -125,44 +255,50 @@
     ALOGI("Registering uinput device %s: touch pad size %dx%d, "
             "max pointers %d.", name, width, height, maxPointers);
 
-    int fd = ::open("/dev/uinput", O_WRONLY | O_NDELAY);
-    if (fd < 0) {
-        ALOGE("Cannot open /dev/uinput: %s.", strerror(errno));
-        return nullptr;
-    }
-
-    struct uinput_user_dev uinp;
-    memset(&uinp, 0, sizeof(struct uinput_user_dev));
-    strlcpy(uinp.name, name, UINPUT_MAX_NAME_SIZE);
-    uinp.id.version = 1;
-    uinp.id.bustype = BUS_VIRTUAL;
-
-    // initialize keymap
     initKeysMap();
 
-    // write device unique id to the phys property
-    ioctl(fd, UI_SET_PHYS, uniqueId);
-
-    // set the keys mapped
-    ioctl(fd, UI_SET_EVBIT, EV_KEY);
-    for (size_t i = 0; i < NELEM(KEYS); i++) {
-        ioctl(fd, UI_SET_KEYBIT, KEYS[i].linuxKeyCode);
-    }
-
-    // register the input device
-    if (write(fd, &uinp, sizeof(uinp)) != sizeof(uinp)) {
-        ALOGE("Cannot write uinput_user_dev to fd %d: %s.", fd, strerror(errno));
-        close(fd);
-        return NULL;
-    }
-    if (ioctl(fd, UI_DEV_CREATE) != 0) {
-        ALOGE("Unable to create uinput device: %s.", strerror(errno));
-        close(fd);
+    UInputDescriptor descriptor;
+    if (!descriptor.Open(name, uniqueId)) {
         return nullptr;
     }
 
-    ALOGV("Created uinput device, fd=%d.", fd);
-    return new NativeConnection(fd, maxPointers);
+    // set the keys mapped
+    for (size_t i = 0; i < NELEM(KEYS); i++) {
+        descriptor.EnableKey(KEYS[i].linuxKeyCode);
+    }
+
+    if (!descriptor.Create()) {
+        return nullptr;
+    }
+
+    return new NativeConnection(descriptor.Detach(), maxPointers, ConnectionType::kRemoteDevice);
+}
+
+NativeConnection* NativeConnection::openGamepad(const char* name, const char* uniqueId) {
+    ALOGI("Registering uinput device %s: gamepad", name);
+
+    UInputDescriptor descriptor;
+    if (!descriptor.Open(name, uniqueId)) {
+        return nullptr;
+    }
+
+    // set the keys mapped for gamepads
+    for (size_t i = 0; i < NELEM(GAMEPAD_KEY_CODES); i++) {
+        descriptor.EnableKey(GAMEPAD_KEY_CODES[i]);
+    }
+
+    // define the axes that are required
+    descriptor.EnableAxesEvents();
+    for (size_t i = 0; i < NELEM(GAMEPAD_AXES); i++) {
+        const Axis& axis = GAMEPAD_AXES[i];
+        descriptor.EnableAxis(axis.number, axis.rangeMin, axis.rangeMax);
+    }
+
+    if (!descriptor.Create()) {
+        return nullptr;
+    }
+
+    return new NativeConnection(descriptor.Detach(), 0, ConnectionType::kGamepadDevice);
 }
 
 void NativeConnection::sendEvent(int32_t type, int32_t code, int32_t value) {
@@ -174,7 +310,6 @@
     write(mFd, &iev, sizeof(iev));
 }
 
-
 static jlong nativeOpen(JNIEnv* env, jclass clazz,
         jstring nameStr, jstring uniqueIdStr,
         jint width, jint height, jint maxPointers) {
@@ -186,6 +321,14 @@
     return reinterpret_cast<jlong>(connection);
 }
 
+static jlong nativeGamepadOpen(JNIEnv* env, jclass clazz, jstring nameStr, jstring uniqueIdStr) {
+    ScopedUtfChars name(env, nameStr);
+    ScopedUtfChars uniqueId(env, uniqueIdStr);
+
+    NativeConnection* connection = NativeConnection::openGamepad(name.c_str(), uniqueId.c_str());
+    return reinterpret_cast<jlong>(connection);
+}
+
 static void nativeClose(JNIEnv* env, jclass clazz, jlong ptr) {
     NativeConnection* connection = reinterpret_cast<NativeConnection*>(ptr);
     delete connection;
@@ -194,6 +337,12 @@
 static void nativeSendKey(JNIEnv* env, jclass clazz, jlong ptr, jint keyCode, jboolean down) {
     int32_t code = getLinuxKeyCode(keyCode);
     NativeConnection* connection = reinterpret_cast<NativeConnection*>(ptr);
+
+    if (connection->IsGamepad()) {
+        ALOGE("Invalid key even for a gamepad - need to send gamepad events");
+        return;
+    }
+
     if (code != KEY_UNKNOWN) {
         connection->sendEvent(EV_KEY, code, down ? 1 : 0);
     } else {
@@ -201,10 +350,44 @@
     }
 }
 
+static void nativeSendGamepadKey(JNIEnv* env, jclass clazz, jlong ptr, jint keyIndex,
+                                 jboolean down) {
+    NativeConnection* connection = reinterpret_cast<NativeConnection*>(ptr);
+
+    if (!connection->IsGamepad()) {
+        ALOGE("Invalid gamepad key for non-gamepad device");
+        return;
+    }
+
+    if ((keyIndex < 0) || (keyIndex >= NELEM(GAMEPAD_KEY_CODES))) {
+        ALOGE("Invalid gamepad key index: %d", keyIndex);
+        return;
+    }
+
+    connection->sendEvent(EV_KEY, GAMEPAD_KEY_CODES[keyIndex], down ? 1 : 0);
+}
+
+static void nativeSendGamepadAxisValue(JNIEnv* env, jclass clazz, jlong ptr, jint axis,
+                                       jint value) {
+    NativeConnection* connection = reinterpret_cast<NativeConnection*>(ptr);
+
+    if (!connection->IsGamepad()) {
+        ALOGE("Invalid axis send for non-gamepad device");
+        return;
+    }
+
+    connection->sendEvent(EV_ABS, axis, value);
+}
+
 static void nativeSendPointerDown(JNIEnv* env, jclass clazz, jlong ptr,
         jint pointerId, jint x, jint y) {
     NativeConnection* connection = reinterpret_cast<NativeConnection*>(ptr);
 
+    if (connection->IsGamepad()) {
+        ALOGE("Invalid pointer down event for a gamepad.");
+        return;
+    }
+
     int32_t slot = findSlot(pointerId);
     if (slot == SLOT_UNKNOWN) {
         slot = assignSlot(pointerId);
@@ -221,6 +404,11 @@
         jint pointerId) {
     NativeConnection* connection = reinterpret_cast<NativeConnection*>(ptr);
 
+    if (connection->IsGamepad()) {
+        ALOGE("Invalid pointer up event for a gamepad.");
+        return;
+    }
+
     int32_t slot = findSlot(pointerId);
     if (slot != SLOT_UNKNOWN) {
         connection->sendEvent(EV_ABS, ABS_MT_SLOT, slot);
@@ -238,17 +426,34 @@
     NativeConnection* connection = reinterpret_cast<NativeConnection*>(ptr);
 
     // Clear keys.
-    for (size_t i = 0; i < NELEM(KEYS); i++) {
-        connection->sendEvent(EV_KEY, KEYS[i].linuxKeyCode, 0);
-    }
+    if (connection->IsRemote()) {
+        for (size_t i = 0; i < NELEM(KEYS); i++) {
+            connection->sendEvent(EV_KEY, KEYS[i].linuxKeyCode, 0);
+        }
 
-    // Clear pointers.
-    int32_t slot = SLOT_UNKNOWN;
-    for (int32_t i = 0; i < connection->getMaxPointers(); i++) {
-        slot = findSlot(i);
-        if (slot != SLOT_UNKNOWN) {
-            connection->sendEvent(EV_ABS, ABS_MT_SLOT, slot);
-            connection->sendEvent(EV_ABS, ABS_MT_TRACKING_ID, -1);
+        // Clear pointers.
+        int32_t slot = SLOT_UNKNOWN;
+        for (int32_t i = 0; i < connection->getMaxPointers(); i++) {
+            slot = findSlot(i);
+            if (slot != SLOT_UNKNOWN) {
+                connection->sendEvent(EV_ABS, ABS_MT_SLOT, slot);
+                connection->sendEvent(EV_ABS, ABS_MT_TRACKING_ID, -1);
+            }
+        }
+    } else {
+        for (size_t i = 0; i < NELEM(GAMEPAD_KEY_CODES); i++) {
+            connection->sendEvent(EV_KEY, GAMEPAD_KEY_CODES[i], 0);
+        }
+
+        for (size_t i = 0; i < NELEM(GAMEPAD_AXES); i++) {
+            const Axis& axis = GAMEPAD_AXES[i];
+            if ((axis.number == ABS_Z) || (axis.number == ABS_RZ)) {
+                // Mark triggers unpressed
+                connection->sendEvent(EV_ABS, axis.number, 0);
+            } else {
+                // Joysticks and dpad rests on center
+                connection->sendEvent(EV_ABS, axis.number, (axis.rangeMin + axis.rangeMax) / 2);
+            }
         }
     }
 
@@ -261,20 +466,16 @@
  */
 
 static JNINativeMethod gUinputBridgeMethods[] = {
-    { "nativeOpen", "(Ljava/lang/String;Ljava/lang/String;III)J",
-        (void*)nativeOpen },
-    { "nativeClose", "(J)V",
-        (void*)nativeClose },
-    { "nativeSendKey", "(JIZ)V",
-        (void*)nativeSendKey },
-    { "nativeSendPointerDown", "(JIII)V",
-        (void*)nativeSendPointerDown },
-    { "nativeSendPointerUp", "(JI)V",
-        (void*)nativeSendPointerUp },
-    { "nativeClear", "(J)V",
-        (void*)nativeClear },
-    { "nativeSendPointerSync", "(J)V",
-        (void*)nativeSendPointerSync },
+        {"nativeOpen", "(Ljava/lang/String;Ljava/lang/String;III)J", (void*)nativeOpen},
+        {"nativeGamepadOpen", "(Ljava/lang/String;Ljava/lang/String;)J", (void*)nativeGamepadOpen},
+        {"nativeClose", "(J)V", (void*)nativeClose},
+        {"nativeSendKey", "(JIZ)V", (void*)nativeSendKey},
+        {"nativeSendPointerDown", "(JIII)V", (void*)nativeSendPointerDown},
+        {"nativeSendPointerUp", "(JI)V", (void*)nativeSendPointerUp},
+        {"nativeClear", "(J)V", (void*)nativeClear},
+        {"nativeSendPointerSync", "(J)V", (void*)nativeSendPointerSync},
+        {"nativeSendGamepadKey", "(JIZ)V", (void*)nativeSendGamepadKey},
+        {"nativeSendGamepadAxisValue", "(JII)V", (void*)nativeSendGamepadAxisValue},
 };
 
 int register_android_server_tv_TvUinputBridge(JNIEnv* env) {
diff --git a/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java b/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java
index 3dd1504..81545d4 100644
--- a/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java
+++ b/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java
@@ -28,6 +28,7 @@
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyInt;
@@ -321,6 +322,11 @@
         // we cannot check installer cert because it seems to be device specific.
         assertEquals(VERSION_CODE, appInstallMetadata.getVersionCode());
         assertFalse(appInstallMetadata.isPreInstalled());
+        // Asserting source stamp not present.
+        assertFalse(appInstallMetadata.isStampPresent());
+        assertFalse(appInstallMetadata.isStampVerified());
+        assertFalse(appInstallMetadata.isStampTrusted());
+        assertNull(appInstallMetadata.getStampCertificateHash());
         // These are hardcoded in the test apk android manifest
         Map<String, String> allowedInstallers =
                 appInstallMetadata.getAllowedInstallersAndCertificates();
diff --git a/tests/net/java/com/android/server/ConnectivityServiceTest.java b/tests/net/java/com/android/server/ConnectivityServiceTest.java
index 8c0c36b..6985415 100644
--- a/tests/net/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/net/java/com/android/server/ConnectivityServiceTest.java
@@ -23,8 +23,6 @@
 import static android.content.pm.PackageManager.MATCH_ANY_USER;
 import static android.content.pm.PackageManager.PERMISSION_DENIED;
 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
-import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
-import static android.net.ConnectivityDiagnosticsManager.DataStallReport;
 import static android.net.ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN;
 import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
 import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_SUPL;
@@ -100,6 +98,7 @@
 import static org.junit.Assert.fail;
 import static org.mockito.ArgumentMatchers.anyLong;
 import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.argThat;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.ArgumentMatchers.startsWith;
 import static org.mockito.Matchers.anyInt;
@@ -6870,8 +6869,13 @@
         HandlerUtilsKt.waitForIdle(mCsHandlerThread, TIMEOUT_MS);
 
         // Verify onConnectivityReport fired
-        verify(mConnectivityDiagnosticsCallback)
-                .onConnectivityReport(any(ConnectivityReport.class));
+        verify(mConnectivityDiagnosticsCallback).onConnectivityReport(
+                argThat(report -> {
+                    final NetworkCapabilities nc = report.getNetworkCapabilities();
+                    return nc.getUids() == null
+                            && nc.getAdministratorUids().isEmpty()
+                            && nc.getOwnerUid() == Process.INVALID_UID;
+                }));
     }
 
     @Test
@@ -6886,7 +6890,13 @@
         HandlerUtilsKt.waitForIdle(mCsHandlerThread, TIMEOUT_MS);
 
         // Verify onDataStallSuspected fired
-        verify(mConnectivityDiagnosticsCallback).onDataStallSuspected(any(DataStallReport.class));
+        verify(mConnectivityDiagnosticsCallback).onDataStallSuspected(
+                argThat(report -> {
+                    final NetworkCapabilities nc = report.getNetworkCapabilities();
+                    return nc.getUids() == null
+                            && nc.getAdministratorUids().isEmpty()
+                            && nc.getOwnerUid() == Process.INVALID_UID;
+                }));
     }
 
     @Test