Merge "Clean up MediaRouter2Manager" into rvc-dev
diff --git a/StubLibraries.bp b/StubLibraries.bp
index 170cac4..91efb05 100644
--- a/StubLibraries.bp
+++ b/StubLibraries.bp
@@ -110,7 +110,7 @@
         },
         last_released: {
             api_file: ":android.api.public.latest",
-            removed_api_file: "api/removed.txt",
+            removed_api_file: ":removed.api.public.latest",
             baseline_file: ":public-api-incompatibilities-with-last-released",
         },
         api_lint: {
@@ -152,7 +152,7 @@
         },
         last_released: {
             api_file: ":android.api.system.latest",
-            removed_api_file: "api/system-removed.txt",
+            removed_api_file: ":removed.api.system.latest",
             baseline_file: ":system-api-incompatibilities-with-last-released"
         },
         api_lint: {
@@ -216,7 +216,7 @@
         },
         last_released: {
             api_file: ":android.api.module-lib.latest",
-            removed_api_file: "api/module-lib-removed.txt",
+            removed_api_file: ":removed.api.module-lib.latest",
             baseline_file: ":module-lib-api-incompatibilities-with-last-released"
         },
         api_lint: {
diff --git a/apex/Android.bp b/apex/Android.bp
index 67cd0d7..51e030b 100644
--- a/apex/Android.bp
+++ b/apex/Android.bp
@@ -74,6 +74,9 @@
             api_file: "api/current.txt",
             removed_api_file: "api/removed.txt",
         },
+        api_lint: {
+            enabled: true,
+        },
     },
     dist: {
         targets: ["sdk", "win_sdk"],
@@ -93,6 +96,9 @@
             api_file: "api/system-current.txt",
             removed_api_file: "api/system-removed.txt",
         },
+        api_lint: {
+            enabled: true,
+        },
     },
     dist: {
         targets: ["sdk", "win_sdk"],
@@ -147,6 +153,9 @@
             api_file: "api/module-lib-current.txt",
             removed_api_file: "api/module-lib-removed.txt",
         },
+        api_lint: {
+            enabled: true,
+        },
     },
     dist: {
         targets: ["sdk", "win_sdk"],
@@ -173,6 +182,9 @@
             api_file: "api/current.txt",
             removed_api_file: "api/removed.txt",
         },
+        api_lint: {
+            enabled: true,
+        },
     },
     dist: {
         targets: ["sdk", "win_sdk"],
diff --git a/apex/media/framework/Android.bp b/apex/media/framework/Android.bp
index a1c886a..3bc4f7b 100644
--- a/apex/media/framework/Android.bp
+++ b/apex/media/framework/Android.bp
@@ -102,6 +102,15 @@
         "framework-media-stubs-srcs-defaults",
         "framework-module-stubs-defaults-publicapi",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-media.api.public.latest",
+            removed_api_file: ":framework-media-removed.api.public.latest",
+        },
+        api_lint: {
+            new_since: ":framework-media.api.public.latest",
+        },
+    },
 }
 
 droidstubs {
@@ -110,6 +119,15 @@
         "framework-media-stubs-srcs-defaults",
         "framework-module-stubs-defaults-systemapi",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-media.api.system.latest",
+            removed_api_file: ":framework-media-removed.api.system.latest",
+        },
+        api_lint: {
+            new_since: ":framework-media.api.system.latest",
+        },
+    },
 }
 
 droidstubs {
@@ -118,6 +136,15 @@
         "framework-media-stubs-srcs-defaults",
         "framework-module-api-defaults-module_libs_api",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-media.api.module-lib.latest",
+            removed_api_file: ":framework-media-removed.api.module-lib.latest",
+        },
+        api_lint: {
+            new_since: ":framework-media.api.module-lib.latest",
+        },
+    },
 }
 
 droidstubs {
diff --git a/apex/permission/framework/Android.bp b/apex/permission/framework/Android.bp
index 3119b7d..68c27a8 100644
--- a/apex/permission/framework/Android.bp
+++ b/apex/permission/framework/Android.bp
@@ -55,6 +55,15 @@
         "framework-module-stubs-defaults-publicapi",
         "framework-permission-stubs-defaults",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-permission.api.public.latest",
+            removed_api_file: ":framework-permission-removed.api.public.latest",
+        },
+        api_lint: {
+            new_since: ":framework-permission.api.public.latest",
+        },
+    },
 }
 
 droidstubs {
@@ -63,6 +72,15 @@
         "framework-module-stubs-defaults-systemapi",
         "framework-permission-stubs-defaults",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-permission.api.system.latest",
+            removed_api_file: ":framework-permission-removed.api.system.latest",
+        },
+        api_lint: {
+            new_since: ":framework-permission.api.system.latest",
+        },
+    },
 }
 
 droidstubs {
@@ -71,6 +89,15 @@
         "framework-module-api-defaults-module_libs_api",
         "framework-permission-stubs-defaults",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-permission.api.module-lib.latest",
+            removed_api_file: ":framework-permission-removed.api.module-lib.latest",
+        },
+        api_lint: {
+            new_since: ":framework-permission.api.module-lib.latest",
+        },
+    },
 }
 
 droidstubs {
diff --git a/apex/permission/service/Android.bp b/apex/permission/service/Android.bp
index 2d92d00..6144976 100644
--- a/apex/permission/service/Android.bp
+++ b/apex/permission/service/Android.bp
@@ -41,6 +41,15 @@
     name: "service-permission-stubs-srcs",
     srcs: [ ":service-permission-sources" ],
     defaults: ["service-module-stubs-srcs-defaults"],
+    check_api: {
+        last_released: {
+            api_file: ":service-permission.api.system-server.latest",
+            removed_api_file: ":service-permission-removed.api.system-server.latest",
+        },
+        api_lint: {
+            new_since: ":service-permission.api.system-server.latest",
+        },
+    },
     visibility: ["//visibility:private"],
     dist: { dest: "service-permission.txt" },
 }
diff --git a/apex/sdkextensions/framework/Android.bp b/apex/sdkextensions/framework/Android.bp
index 6a78711..14e23ed 100644
--- a/apex/sdkextensions/framework/Android.bp
+++ b/apex/sdkextensions/framework/Android.bp
@@ -57,6 +57,15 @@
         "framework-module-stubs-defaults-publicapi",
         "framework-sdkextensions-stubs-defaults",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-sdkextensions.api.public.latest",
+            removed_api_file: ":framework-sdkextensions-removed.api.public.latest",
+        },
+        api_lint: {
+            new_since: ":framework-sdkextensions.api.public.latest",
+        },
+    },
 }
 
 droidstubs {
@@ -65,6 +74,15 @@
         "framework-module-stubs-defaults-systemapi",
         "framework-sdkextensions-stubs-defaults",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-sdkextensions.api.system.latest",
+            removed_api_file: ":framework-sdkextensions-removed.api.system.latest",
+        },
+        api_lint: {
+            new_since: ":framework-sdkextensions.api.system.latest",
+        },
+    },
 }
 
 droidstubs {
@@ -73,6 +91,15 @@
         "framework-module-api-defaults-module_libs_api",
         "framework-sdkextensions-stubs-defaults",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-sdkextensions.api.module-lib.latest",
+            removed_api_file: ":framework-sdkextensions-removed.api.module-lib.latest",
+        },
+        api_lint: {
+            new_since: ":framework-sdkextensions.api.module-lib.latest",
+        },
+    },
 }
 
 droidstubs {
diff --git a/apex/statsd/framework/Android.bp b/apex/statsd/framework/Android.bp
index 7d0f2ee..9f5d933 100644
--- a/apex/statsd/framework/Android.bp
+++ b/apex/statsd/framework/Android.bp
@@ -93,6 +93,15 @@
         "framework-module-stubs-defaults-publicapi",
         "framework-statsd-stubs-srcs-defaults",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-statsd.api.public.latest",
+            removed_api_file: ":framework-statsd-removed.api.public.latest",
+        },
+        api_lint: {
+            new_since: ":framework-statsd.api.public.latest",
+        },
+    },
 }
 
 droidstubs {
@@ -101,6 +110,15 @@
         "framework-module-stubs-defaults-systemapi",
         "framework-statsd-stubs-srcs-defaults",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-statsd.api.system.latest",
+            removed_api_file: ":framework-statsd-removed.api.system.latest",
+        },
+        api_lint: {
+            new_since: ":framework-statsd.api.system.latest",
+        },
+    },
 }
 
 droidstubs {
@@ -109,6 +127,15 @@
         "framework-module-api-defaults-module_libs_api",
         "framework-statsd-stubs-srcs-defaults",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-statsd.api.module-lib.latest",
+            removed_api_file: ":framework-statsd-removed.api.module-lib.latest",
+        },
+        api_lint: {
+            new_since: ":framework-statsd.api.module-lib.latest",
+        },
+    },
 }
 
 droidstubs {
diff --git a/api/test-current.txt b/api/test-current.txt
index cc3604c..46049bd 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -431,6 +431,7 @@
   }
 
   public class DreamManager {
+    method @RequiresPermission("android.permission.READ_DREAM_STATE") public boolean isDreaming();
     method @RequiresPermission("android.permission.WRITE_DREAM_STATE") public void setActiveDream(@NonNull android.content.ComponentName);
     method @RequiresPermission("android.permission.WRITE_DREAM_STATE") public void startDream(@NonNull android.content.ComponentName);
     method @RequiresPermission("android.permission.WRITE_DREAM_STATE") public void stopDream();
diff --git a/core/java/android/app/DreamManager.java b/core/java/android/app/DreamManager.java
index fe13b8f..f236813 100644
--- a/core/java/android/app/DreamManager.java
+++ b/core/java/android/app/DreamManager.java
@@ -58,7 +58,7 @@
     @RequiresPermission(android.Manifest.permission.WRITE_DREAM_STATE)
     public void startDream(@NonNull ComponentName name) {
         try {
-            mService.testDream(mContext.getUserId(), name);
+            mService.dream();
         } catch (RemoteException e) {
             e.rethrowFromSystemServer();
         }
@@ -99,4 +99,22 @@
             e.rethrowFromSystemServer();
         }
     }
+
+    /**
+     * Returns whether the device is Dreaming.
+     *
+     * <p> This is only used for testing the dream service APIs.
+     *
+     * @hide
+     */
+    @TestApi
+    @RequiresPermission(android.Manifest.permission.READ_DREAM_STATE)
+    public boolean isDreaming() {
+        try {
+            return mService.isDreaming();
+        } catch (RemoteException e) {
+            e.rethrowFromSystemServer();
+        }
+        return false;
+    }
 }
diff --git a/core/java/android/view/WindowlessWindowManager.java b/core/java/android/view/WindowlessWindowManager.java
index 95d6d65..15604a2 100644
--- a/core/java/android/view/WindowlessWindowManager.java
+++ b/core/java/android/view/WindowlessWindowManager.java
@@ -41,6 +41,7 @@
     private final static String TAG = "WindowlessWindowManager";
 
     private class State {
+        //TODO : b/150190730 we should create it when view show and release it when view invisible.
         SurfaceControl mSurfaceControl;
         WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();
         int mDisplayId;
@@ -239,21 +240,19 @@
         }
         WindowManager.LayoutParams attrs = state.mParams;
 
-        final Rect surfaceInsets = attrs.surfaceInsets;
-        int width = surfaceInsets != null ?
-                attrs.width + surfaceInsets.left + surfaceInsets.right : attrs.width;
-        int height = surfaceInsets != null ?
-                attrs.height + surfaceInsets.top + surfaceInsets.bottom : attrs.height;
-
-        t.setBufferSize(sc, width, height)
-            .setOpaque(sc, isOpaque(attrs));
         if (viewFlags == View.VISIBLE) {
-            t.show(sc);
+            final Rect surfaceInsets = attrs.surfaceInsets;
+            int width = surfaceInsets != null
+                    ? attrs.width + surfaceInsets.left + surfaceInsets.right : attrs.width;
+            int height = surfaceInsets != null
+                    ? attrs.height + surfaceInsets.top + surfaceInsets.bottom : attrs.height;
+
+            t.setBufferSize(sc, width, height).setOpaque(sc, isOpaque(attrs)).show(sc).apply();
+            outSurfaceControl.copyFrom(sc);
         } else {
-            t.hide(sc);
+            t.hide(sc).apply();
+            outSurfaceControl.release();
         }
-        t.apply();
-        outSurfaceControl.copyFrom(sc);
         outFrame.set(0, 0, attrs.width, attrs.height);
 
         mergedConfiguration.setConfiguration(mConfiguration, mConfiguration);
diff --git a/media/java/android/media/tv/TvInputManager.java b/media/java/android/media/tv/TvInputManager.java
index f058a02..e701055 100644
--- a/media/java/android/media/tv/TvInputManager.java
+++ b/media/java/android/media/tv/TvInputManager.java
@@ -1805,7 +1805,7 @@
             String tvInputSessionId, int priorityHint,
             Executor executor, final HardwareCallback callback) {
         try {
-            return new Hardware(
+            ITvInputHardware hardware =
                     mService.acquireTvInputHardware(deviceId, new ITvInputHardwareCallback.Stub() {
                 @Override
                 public void onReleased() {
@@ -1826,7 +1826,11 @@
                                 Binder.restoreCallingIdentity(identity);
                             }
                 }
-                    }, info, mUserId, tvInputSessionId, priorityHint));
+                    }, info, mUserId, tvInputSessionId, priorityHint);
+            if (hardware == null) {
+                return null;
+            }
+            return new Hardware(hardware);
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
diff --git a/media/java/android/media/tv/tunerresourcemanager/ResourceClientProfile.java b/media/java/android/media/tv/tunerresourcemanager/ResourceClientProfile.java
index 598ff8f..28f1ac9 100644
--- a/media/java/android/media/tv/tunerresourcemanager/ResourceClientProfile.java
+++ b/media/java/android/media/tv/tunerresourcemanager/ResourceClientProfile.java
@@ -17,6 +17,7 @@
 package android.media.tv.tunerresourcemanager;
 
 import android.annotation.NonNull;
+import android.annotation.Nullable;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.util.Log;
@@ -81,7 +82,7 @@
      *                OEM. The id of the useCaseVendor should be passed through this parameter. Any
      *                undefined use case would cause IllegalArgumentException.
      */
-    public ResourceClientProfile(@NonNull String tvInputSessionId,
+    public ResourceClientProfile(@Nullable String tvInputSessionId,
                                  int useCase) {
         mTvInputSessionId = tvInputSessionId;
         mUseCase = useCase;
@@ -92,7 +93,7 @@
      *
      * @return the value of the tv input session id.
      */
-    @NonNull
+    @Nullable
     public String getTvInputSessionId() {
         return mTvInputSessionId;
     }
diff --git a/packages/SystemUI/src/com/android/systemui/wm/SystemWindows.java b/packages/SystemUI/src/com/android/systemui/wm/SystemWindows.java
index 64cac84..93f45c5 100644
--- a/packages/SystemUI/src/com/android/systemui/wm/SystemWindows.java
+++ b/packages/SystemUI/src/com/android/systemui/wm/SystemWindows.java
@@ -189,8 +189,8 @@
     public SurfaceControl getViewSurface(View rootView) {
         for (int i = 0; i < mPerDisplay.size(); ++i) {
             for (int iWm = 0; iWm < mPerDisplay.valueAt(i).mWwms.size(); ++iWm) {
-                SurfaceControl out =
-                        mPerDisplay.valueAt(i).mWwms.get(iWm).getSurfaceControlForWindow(rootView);
+                SurfaceControl out = mPerDisplay.valueAt(i).mWwms.valueAt(iWm)
+                        .getSurfaceControlForWindow(rootView);
                 if (out != null) {
                     return out;
                 }
diff --git a/packages/Tethering/common/TetheringLib/Android.bp b/packages/Tethering/common/TetheringLib/Android.bp
index 8ae1593..d029d2b 100644
--- a/packages/Tethering/common/TetheringLib/Android.bp
+++ b/packages/Tethering/common/TetheringLib/Android.bp
@@ -94,6 +94,15 @@
         "framework-module-stubs-defaults-publicapi",
         "framework-tethering-stubs-defaults",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-tethering.api.public.latest",
+            removed_api_file: ":framework-tethering-removed.api.public.latest",
+        },
+        api_lint: {
+            new_since: ":framework-tethering.api.public.latest",
+        },
+    },
 }
 
 droidstubs {
@@ -102,6 +111,15 @@
         "framework-module-stubs-defaults-systemapi",
         "framework-tethering-stubs-defaults",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-tethering.api.system.latest",
+            removed_api_file: ":framework-tethering-removed.api.system.latest",
+        },
+        api_lint: {
+            new_since: ":framework-tethering.api.system.latest",
+        },
+    },
 }
 
 droidstubs {
@@ -110,6 +128,15 @@
         "framework-module-api-defaults-module_libs_api",
         "framework-tethering-stubs-defaults",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-tethering.api.module-lib.latest",
+            removed_api_file: ":framework-tethering-removed.api.module-lib.latest",
+        },
+        api_lint: {
+            new_since: ":framework-tethering.api.module-lib.latest",
+        },
+    },
 }
 
 droidstubs {
diff --git a/services/Android.bp b/services/Android.bp
index 2e70f1c..a07bb28 100644
--- a/services/Android.bp
+++ b/services/Android.bp
@@ -135,7 +135,7 @@
         },
         last_released: {
             api_file: ":android.api.system-server.latest",
-            removed_api_file: "api/removed.txt",
+            removed_api_file: ":removed.api.system-server.latest",
             baseline_file: ":system-server-api-incompatibilities-with-last-released"
         },
         api_lint: {
diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java
index 14fe0c5..be53945 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -1579,6 +1579,14 @@
                 writeSettingsLocked();
             }
         }
+
+        if (newState == VolumeInfo.STATE_MOUNTED) {
+            // Private volumes can be unmounted and re-mounted even after a user has
+            // been unlocked; on devices that support encryption keys tied to the filesystem,
+            // this requires setting up the keys again.
+            prepareUserStorageIfNeeded(vol);
+        }
+
         // This is a blocking call to Storage Service which needs to process volume state changed
         // before notifying other listeners.
         // Intentionally called without the mLock to avoid deadlocking from the Storage Service.
@@ -3266,10 +3274,38 @@
         }
     }
 
+    private void prepareUserStorageIfNeeded(VolumeInfo vol) {
+        if (vol.type != VolumeInfo.TYPE_PRIVATE) {
+            return;
+        }
+
+        final UserManager um = mContext.getSystemService(UserManager.class);
+        final UserManagerInternal umInternal =
+                LocalServices.getService(UserManagerInternal.class);
+
+        for (UserInfo user : um.getUsers(false /* includeDying */)) {
+            final int flags;
+            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
+                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
+            } else if (umInternal.isUserRunning(user.id)) {
+                flags = StorageManager.FLAG_STORAGE_DE;
+            } else {
+                continue;
+            }
+
+            prepareUserStorageInternal(vol.fsUuid, user.id, user.serialNumber, flags);
+        }
+    }
+
     @Override
     public void prepareUserStorage(String volumeUuid, int userId, int serialNumber, int flags) {
         enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
 
+        prepareUserStorageInternal(volumeUuid, userId, serialNumber, flags);
+    }
+
+    private void prepareUserStorageInternal(String volumeUuid, int userId, int serialNumber,
+            int flags) {
         try {
             mVold.prepareUserStorage(volumeUuid, userId, serialNumber, flags);
             // After preparing user storage, we should check if we should mount data mirror again,
diff --git a/services/core/java/com/android/server/display/DisplayPowerController.java b/services/core/java/com/android/server/display/DisplayPowerController.java
index bafeb77..9411c562 100644
--- a/services/core/java/com/android/server/display/DisplayPowerController.java
+++ b/services/core/java/com/android/server/display/DisplayPowerController.java
@@ -1067,12 +1067,22 @@
                     mColorFadeEnabled && mPowerState.getColorFadeLevel() == 1.0f;
             final boolean brightnessIsTemporary =
                     mAppliedTemporaryBrightness || mAppliedTemporaryAutoBrightnessAdjustment;
-            if (initialRampSkip || hasBrightnessBuckets
-                    || wasOrWillBeInVr || !isDisplayContentVisible || brightnessIsTemporary) {
-                animateScreenBrightness(brightnessState, SCREEN_ANIMATION_RATE_MINIMUM);
-            } else {
-                animateScreenBrightness(brightnessState,
-                        slowChange ? mBrightnessRampRateSlow : mBrightnessRampRateFast);
+            // We only want to animate the brightness if it is between 0.0f and 1.0f.
+            // brightnessState can contain the values -1.0f and NaN, which we do not want to
+            // animate to. To avoid this, we check the value first.
+            // If the brightnessState is off (-1.0f) we still want to animate to the minimum
+            // brightness (0.0f) to accommodate for LED displays, which can appear bright to the
+            // user even when the display is all black.
+            float animateValue = brightnessState == PowerManager.BRIGHTNESS_OFF_FLOAT
+                    ? PowerManager.BRIGHTNESS_MIN : brightnessState;
+            if (isValidBrightnessValue(animateValue)) {
+                if (initialRampSkip || hasBrightnessBuckets
+                        || wasOrWillBeInVr || !isDisplayContentVisible || brightnessIsTemporary) {
+                    animateScreenBrightness(animateValue, SCREEN_ANIMATION_RATE_MINIMUM);
+                } else {
+                    animateScreenBrightness(animateValue,
+                            slowChange ? mBrightnessRampRateSlow : mBrightnessRampRateFast);
+                }
             }
 
             if (!brightnessIsTemporary) {
diff --git a/services/core/java/com/android/server/display/DisplayPowerState.java b/services/core/java/com/android/server/display/DisplayPowerState.java
index 24e1b4e..4b6430d 100644
--- a/services/core/java/com/android/server/display/DisplayPowerState.java
+++ b/services/core/java/com/android/server/display/DisplayPowerState.java
@@ -146,7 +146,7 @@
     /**
      * Sets the display brightness.
      *
-     * @param brightness The brightness, ranges from 0 (minimum / off) to 255 (brightest).
+     * @param brightness The brightness, ranges from 0.0f (minimum / off) to 1.0f (brightest).
      */
     public void setScreenBrightness(float brightness) {
         if (mScreenBrightness != brightness) {
diff --git a/services/core/java/com/android/server/tv/TvInputHardwareManager.java b/services/core/java/com/android/server/tv/TvInputHardwareManager.java
index 8f71943..2314afc 100755
--- a/services/core/java/com/android/server/tv/TvInputHardwareManager.java
+++ b/services/core/java/com/android/server/tv/TvInputHardwareManager.java
@@ -46,6 +46,8 @@
 import android.media.tv.TvInputInfo;
 import android.media.tv.TvInputService.PriorityHintUseCaseType;
 import android.media.tv.TvStreamConfig;
+import android.media.tv.tunerresourcemanager.ResourceClientProfile;
+import android.media.tv.tunerresourcemanager.TunerResourceManager;
 import android.os.Handler;
 import android.os.IBinder;
 import android.os.Message;
@@ -179,7 +181,7 @@
                 Slog.e(TAG, "onDeviceUnavailable: Cannot find a connection with " + deviceId);
                 return;
             }
-            connection.resetLocked(null, null, null, null, null);
+            connection.resetLocked(null, null, null, null, null, null);
             mConnections.remove(deviceId);
             buildHardwareListLocked();
             TvInputHardwareInfo info = connection.getHardwareInfoLocked();
@@ -369,25 +371,34 @@
         if (callback == null) {
             throw new NullPointerException();
         }
+        TunerResourceManager trm = (TunerResourceManager) mContext.getSystemService(
+                Context.TV_TUNER_RESOURCE_MGR_SERVICE);
         synchronized (mLock) {
             Connection connection = mConnections.get(deviceId);
             if (connection == null) {
                 Slog.e(TAG, "Invalid deviceId : " + deviceId);
                 return null;
             }
-            // TODO: check with TRM to compare the client's priority with the current holder's
-            // priority. If lower, do nothing.
-            if (checkUidChangedLocked(connection, callingUid, resolvedUserId)) {
-                TvInputHardwareImpl hardware =
-                        new TvInputHardwareImpl(connection.getHardwareInfoLocked());
-                try {
-                    callback.asBinder().linkToDeath(connection, 0);
-                } catch (RemoteException e) {
-                    hardware.release();
-                    return null;
-                }
-                connection.resetLocked(hardware, callback, info, callingUid, resolvedUserId);
+
+            ResourceClientProfile profile =
+                    new ResourceClientProfile(tvInputSessionId, priorityHint);
+            ResourceClientProfile holderProfile = connection.getResourceClientProfileLocked();
+            if (holderProfile != null && trm != null
+                    && !trm.isHigherPriority(profile, holderProfile)) {
+                Slog.d(TAG, "Acquiring does not show higher priority than the current holder."
+                        + " Device id:" + deviceId);
+                return null;
             }
+            TvInputHardwareImpl hardware =
+                    new TvInputHardwareImpl(connection.getHardwareInfoLocked());
+            try {
+                callback.asBinder().linkToDeath(connection, 0);
+            } catch (RemoteException e) {
+                hardware.release();
+                return null;
+            }
+            connection.resetLocked(hardware, callback, info, callingUid, resolvedUserId,
+                    profile);
             return connection.getHardwareLocked();
         }
     }
@@ -411,7 +422,7 @@
             if (callback != null) {
                 callback.asBinder().unlinkToDeath(connection, 0);
             }
-            connection.resetLocked(null, null, null, null, null);
+            connection.resetLocked(null, null, null, null, null, null);
         }
     }
 
@@ -621,6 +632,7 @@
         private Integer mCallingUid = null;
         private Integer mResolvedUserId = null;
         private Runnable mOnFirstFrameCaptured;
+        private ResourceClientProfile mResourceClientProfile = null;
 
         public Connection(TvInputHardwareInfo hardwareInfo) {
             mHardwareInfo = hardwareInfo;
@@ -629,7 +641,8 @@
         // *Locked methods assume TvInputHardwareManager.mLock is held.
 
         public void resetLocked(TvInputHardwareImpl hardware, ITvInputHardwareCallback callback,
-                TvInputInfo info, Integer callingUid, Integer resolvedUserId) {
+                TvInputInfo info, Integer callingUid, Integer resolvedUserId,
+                ResourceClientProfile profile) {
             if (mHardware != null) {
                 try {
                     mCallback.onReleased();
@@ -644,6 +657,7 @@
             mCallingUid = callingUid;
             mResolvedUserId = resolvedUserId;
             mOnFirstFrameCaptured = null;
+            mResourceClientProfile = profile;
 
             if (mHardware != null && mCallback != null) {
                 try {
@@ -698,10 +712,14 @@
             return mOnFirstFrameCaptured;
         }
 
+        public ResourceClientProfile getResourceClientProfileLocked() {
+            return mResourceClientProfile;
+        }
+
         @Override
         public void binderDied() {
             synchronized (mLock) {
-                resetLocked(null, null, null, null, null);
+                resetLocked(null, null, null, null, null, null);
             }
         }
 
@@ -713,6 +731,7 @@
                     + ", mConfigs: " + Arrays.toString(mConfigs)
                     + ", mCallingUid: " + mCallingUid
                     + ", mResolvedUserId: " + mResolvedUserId
+                    + ", mResourceClientProfile: " + mResourceClientProfile
                     + " }";
         }
 
diff --git a/services/core/java/com/android/server/tv/tunerresourcemanager/TunerResourceManagerService.java b/services/core/java/com/android/server/tv/tunerresourcemanager/TunerResourceManagerService.java
index 2f70840..41aa4ee 100644
--- a/services/core/java/com/android/server/tv/tunerresourcemanager/TunerResourceManagerService.java
+++ b/services/core/java/com/android/server/tv/tunerresourcemanager/TunerResourceManagerService.java
@@ -18,6 +18,8 @@
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.app.ActivityManager;
+import android.app.ActivityManager.RunningAppProcessInfo;
 import android.content.Context;
 import android.media.tv.TvInputManager;
 import android.media.tv.tunerresourcemanager.CasSessionRequest;
@@ -42,6 +44,7 @@
 
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
@@ -71,7 +74,8 @@
     @GuardedBy("mLock")
     private Map<Integer, ResourcesReclaimListenerRecord> mListeners = new HashMap<>();
 
-    private TvInputManager mManager;
+    private TvInputManager mTvInputManager;
+    private ActivityManager mActivityManager;
     private UseCasePriorityHints mPriorityCongfig = new UseCasePriorityHints();
 
     // An internal resource request count to help generate resource handle.
@@ -94,7 +98,9 @@
         if (!isForTesting) {
             publishBinderService(Context.TV_TUNER_RESOURCE_MGR_SERVICE, new BinderService());
         }
-        mManager = (TvInputManager) getContext().getSystemService(Context.TV_INPUT_SERVICE);
+        mTvInputManager = (TvInputManager) getContext().getSystemService(Context.TV_INPUT_SERVICE);
+        mActivityManager =
+                (ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE);
         mPriorityCongfig.parse();
     }
 
@@ -204,7 +210,7 @@
 
         @Override
         public boolean requestDemux(@NonNull TunerDemuxRequest request,
-                    @NonNull int[] demuxHandle)  throws RemoteException {
+                    @NonNull int[] demuxHandle) throws RemoteException {
             enforceTunerAccessPermission("requestDemux");
             enforceTrmAccessPermission("requestDemux");
             if (demuxHandle == null) {
@@ -362,14 +368,15 @@
 
         @Override
         public boolean isHigherPriority(
-                ResourceClientProfile challengerProfile, ResourceClientProfile holderProfile) {
+                ResourceClientProfile challengerProfile, ResourceClientProfile holderProfile)
+                throws RemoteException {
             enforceTrmAccessPermission("isHigherPriority");
-            if (DEBUG) {
-                Slog.d(TAG,
-                        "isHigherPriority(challengerProfile=" + challengerProfile
-                                + ", holderProfile=" + challengerProfile + ")");
+            if (challengerProfile == null || holderProfile == null) {
+                throw new RemoteException("Client profiles can't be null.");
             }
-            return true;
+            synchronized (mLock) {
+                return isHigherPriorityInternal(challengerProfile, holderProfile);
+            }
         }
     }
 
@@ -381,7 +388,7 @@
         }
 
         clientId[0] = INVALID_CLIENT_ID;
-        if (mManager == null) {
+        if (mTvInputManager == null) {
             Slog.e(TAG, "TvInputManager is null. Can't register client profile.");
             return;
         }
@@ -390,7 +397,7 @@
 
         int pid = profile.getTvInputSessionId() == null
                 ? Binder.getCallingPid() /*callingPid*/
-                : mManager.getClientPid(profile.getTvInputSessionId()); /*tvAppId*/
+                : mTvInputManager.getClientPid(profile.getTvInputSessionId()); /*tvAppId*/
 
         ClientProfile clientProfile = new ClientProfile.Builder(clientId[0])
                                               .tvInputSessionId(profile.getTvInputSessionId())
@@ -693,6 +700,33 @@
     }
 
     @VisibleForTesting
+    protected boolean isHigherPriorityInternal(ResourceClientProfile challengerProfile,
+            ResourceClientProfile holderProfile) {
+        if (DEBUG) {
+            Slog.d(TAG,
+                    "isHigherPriority(challengerProfile=" + challengerProfile
+                            + ", holderProfile=" + challengerProfile + ")");
+        }
+        if (mTvInputManager == null) {
+            Slog.e(TAG, "TvInputManager is null. Can't compare the priority.");
+            // Allow the client to acquire the hardware interface
+            // when the TRM is not able to compare the priority.
+            return true;
+        }
+
+        int challengerPid = challengerProfile.getTvInputSessionId() == null
+                ? Binder.getCallingPid() /*callingPid*/
+                : mTvInputManager.getClientPid(challengerProfile.getTvInputSessionId()); /*tvAppId*/
+        int holderPid = holderProfile.getTvInputSessionId() == null
+                ? Binder.getCallingPid() /*callingPid*/
+                : mTvInputManager.getClientPid(holderProfile.getTvInputSessionId()); /*tvAppId*/
+
+        int challengerPriority = getClientPriority(challengerProfile.getUseCase(), challengerPid);
+        int holderPriority = getClientPriority(holderProfile.getUseCase(), holderPid);
+        return challengerPriority > holderPriority;
+    }
+
+    @VisibleForTesting
     protected void releaseFrontendInternal(FrontendResource fe) {
         if (DEBUG) {
             Slog.d(TAG, "releaseFrontend(id=" + fe.getId() + ")");
@@ -818,8 +852,20 @@
 
     @VisibleForTesting
     protected boolean isForeground(int pid) {
-        // TODO: how to get fg/bg information from pid
-        return true;
+        if (mActivityManager == null) {
+            return false;
+        }
+        List<RunningAppProcessInfo> appProcesses = mActivityManager.getRunningAppProcesses();
+        if (appProcesses == null) {
+            return false;
+        }
+        for (RunningAppProcessInfo appProcess : appProcesses) {
+            if (appProcess.pid == pid
+                    && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
+                return true;
+            }
+        }
+        return false;
     }
 
     private void updateFrontendClientMappingOnNewGrant(int grantingId, int ownerClientId) {
@@ -1044,7 +1090,7 @@
     }
 
     private void enforceTrmAccessPermission(String apiName) {
-        getContext().enforceCallingPermission("android.permission.TUNER_RESOURCE_ACCESS",
+        getContext().enforceCallingOrSelfPermission("android.permission.TUNER_RESOURCE_ACCESS",
                 TAG + ": " + apiName);
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/tv/tunerresourcemanager/TunerResourceManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/tv/tunerresourcemanager/TunerResourceManagerServiceTest.java
index 21af356..f934323 100644
--- a/services/tests/servicestests/src/com/android/server/tv/tunerresourcemanager/TunerResourceManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/tv/tunerresourcemanager/TunerResourceManagerServiceTest.java
@@ -64,6 +64,7 @@
     private Context mContextSpy;
     @Mock private ITvInputManager mITvInputManagerMock;
     private TunerResourceManagerService mTunerResourceManagerService;
+    private boolean mIsForeground;
 
     private static final class TestResourcesReclaimListener extends IResourcesReclaimListener.Stub {
         boolean mReclaimed;
@@ -104,7 +105,12 @@
         TvInputManager tvInputManager = new TvInputManager(mITvInputManagerMock, 0);
         mContextSpy = spy(new ContextWrapper(InstrumentationRegistry.getTargetContext()));
         when(mContextSpy.getSystemService(Context.TV_INPUT_SERVICE)).thenReturn(tvInputManager);
-        mTunerResourceManagerService = new TunerResourceManagerService(mContextSpy);
+        mTunerResourceManagerService = new TunerResourceManagerService(mContextSpy) {
+            @Override
+            protected boolean isForeground(int pid) {
+                return mIsForeground;
+            }
+        };
         mTunerResourceManagerService.onStart(true /*isForTesting*/);
     }
 
@@ -737,4 +743,22 @@
                 .isTrue();
         assertThat(mTunerResourceManagerService.getResourceIdFromHandle(desHandle[0])).isEqualTo(0);
     }
+
+    @Test
+    public void isHigherPriorityTest() {
+        mIsForeground = false;
+        ResourceClientProfile backgroundPlaybackProfile =
+                new ResourceClientProfile(null /*sessionId*/,
+                        TvInputService.PRIORITY_HINT_USE_CASE_TYPE_PLAYBACK);
+        ResourceClientProfile backgroundRecordProfile =
+                new ResourceClientProfile(null /*sessionId*/,
+                        TvInputService.PRIORITY_HINT_USE_CASE_TYPE_RECORD);
+        int backgroundPlaybackPriority = mTunerResourceManagerService.getClientPriority(
+                TvInputService.PRIORITY_HINT_USE_CASE_TYPE_PLAYBACK, 0);
+        int backgroundRecordPriority = mTunerResourceManagerService.getClientPriority(
+                TvInputService.PRIORITY_HINT_USE_CASE_TYPE_RECORD, 0);
+        assertThat(mTunerResourceManagerService.isHigherPriorityInternal(backgroundPlaybackProfile,
+                backgroundRecordProfile)).isEqualTo(
+                        (backgroundPlaybackPriority > backgroundRecordPriority));
+    }
 }
diff --git a/wifi/Android.bp b/wifi/Android.bp
index 6a8600a..1e2c81a 100644
--- a/wifi/Android.bp
+++ b/wifi/Android.bp
@@ -143,6 +143,16 @@
         "framework-module-stubs-defaults-publicapi",
         "framework-wifi-stubs-srcs-defaults",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-wifi.api.public.latest",
+            removed_api_file: ":framework-wifi-removed.api.public.latest",
+        },
+        api_lint: {
+            new_since: ":framework-wifi.api.public.latest",
+            baseline_file: "api/lint-baseline.txt",
+        },
+    },
 }
 
 droidstubs {
@@ -151,6 +161,16 @@
         "framework-module-stubs-defaults-systemapi",
         "framework-wifi-stubs-srcs-defaults",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-wifi.api.system.latest",
+            removed_api_file: ":framework-wifi-removed.api.system.latest",
+        },
+        api_lint: {
+            new_since: ":framework-wifi.api.system.latest",
+            baseline_file: "api/system-lint-baseline.txt",
+        },
+    },
 }
 
 droidstubs {
@@ -159,6 +179,15 @@
         "framework-module-api-defaults-module_libs_api",
         "framework-wifi-stubs-srcs-defaults",
     ],
+    check_api: {
+        last_released: {
+            api_file: ":framework-wifi.api.module-lib.latest",
+            removed_api_file: ":framework-wifi-removed.api.module-lib.latest",
+        },
+        api_lint: {
+            new_since: ":framework-wifi.api.module-lib.latest",
+        },
+    },
 }
 
 droidstubs {
diff --git a/wifi/api/lint-baseline.txt b/wifi/api/lint-baseline.txt
new file mode 100644
index 0000000..892411f
--- /dev/null
+++ b/wifi/api/lint-baseline.txt
@@ -0,0 +1,13 @@
+// Baseline format: 1.0
+GenericException: android.net.wifi.WifiManager.LocalOnlyHotspotReservation#finalize():
+    Methods must not throw generic exceptions (`java.lang.Throwable`)
+GenericException: android.net.wifi.WifiManager.MulticastLock#finalize():
+    Methods must not throw generic exceptions (`java.lang.Throwable`)
+GenericException: android.net.wifi.WifiManager.WifiLock#finalize():
+    Methods must not throw generic exceptions (`java.lang.Throwable`)
+
+
+VisiblySynchronized: PsiThisExpression:WifiManager.this:
+    Internal locks must not be exposed (synchronizing on this or class is still externally observable): method android.net.wifi.WifiManager.WifiLock.finalize()
+VisiblySynchronized: android.net.wifi.WifiManager.WifiLock#finalize():
+    Internal locks must not be exposed (synchronizing on this or class is still externally observable): method android.net.wifi.WifiManager.WifiLock.finalize()
diff --git a/wifi/api/system-lint-baseline.txt b/wifi/api/system-lint-baseline.txt
new file mode 100644
index 0000000..6547ee8
--- /dev/null
+++ b/wifi/api/system-lint-baseline.txt
@@ -0,0 +1,6 @@
+// Baseline format: 1.0
+MissingGetterMatchingBuilder: android.net.wifi.rtt.RangingRequest.Builder#addResponder(android.net.wifi.rtt.ResponderConfig):
+    android.net.wifi.rtt.RangingRequest does not declare a `getResponders()` method matching method android.net.wifi.rtt.RangingRequest.Builder.addResponder(android.net.wifi.rtt.ResponderConfig)
+
+MissingNullability: android.net.wifi.rtt.RangingRequest.Builder#addResponder(android.net.wifi.rtt.ResponderConfig):
+