Fix a bug that onOpChanged callbacks are not called.

For a newly installed app, evalForegroundOps is not called when the
app's location permission is while in use. Also, uidState was committed
before comparing with the pending state.

Bug: 129093959, 126269233
Test: Manual, atest android.app.appops.cts.AppOpsTest
Change-Id: Ib9d209351e172275e891975a1de342a1599f98c3
diff --git a/services/core/java/com/android/server/appop/AppOpsService.java b/services/core/java/com/android/server/appop/AppOpsService.java
index 10b67c1..2e5dd3b 100644
--- a/services/core/java/com/android/server/appop/AppOpsService.java
+++ b/services/core/java/com/android/server/appop/AppOpsService.java
@@ -1257,6 +1257,7 @@
                 }
                 scheduleWriteLocked();
             }
+            uidState.evalForegroundOps(mOpModeWatchers);
         }
 
         String[] uidPackageNames = getPackagesForUid(uid);
@@ -2414,8 +2415,6 @@
     private void commitUidPendingStateLocked(UidState uidState) {
         final boolean lastForeground = uidState.state <= UID_STATE_MAX_LAST_NON_RESTRICTED;
         final boolean nowForeground = uidState.pendingState <= UID_STATE_MAX_LAST_NON_RESTRICTED;
-        uidState.state = uidState.pendingState;
-        uidState.pendingStateCommitTime = 0;
         if (uidState.hasForegroundWatchers && lastForeground != nowForeground) {
             for (int fgi = uidState.foregroundOps.size() - 1; fgi >= 0; fgi--) {
                 if (!uidState.foregroundOps.valueAt(fgi)) {
@@ -2424,11 +2423,10 @@
                 final int code = uidState.foregroundOps.keyAt(fgi);
                 // For location ops we consider fg state only if the fg service
                 // is of location type, for all other ops any fg service will do.
-                final long resolvedLastRestrictedUidState = resolveFirstUnrestrictedUidState(code);
-                final boolean resolvedLastFg = uidState.state <= resolvedLastRestrictedUidState;
-                final boolean resolvedNowBg = uidState.pendingState
-                        <= resolvedLastRestrictedUidState;
-                if (resolvedLastFg == resolvedNowBg) {
+                final long firstUnrestrictedUidState = resolveFirstUnrestrictedUidState(code);
+                final boolean resolvedLastFg = uidState.state <= firstUnrestrictedUidState;
+                final boolean resolvedNowFg = uidState.pendingState <= firstUnrestrictedUidState;
+                if (resolvedLastFg == resolvedNowFg) {
                     continue;
                 }
                 final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
@@ -2460,6 +2458,8 @@
                 }
             }
         }
+        uidState.state = uidState.pendingState;
+        uidState.pendingStateCommitTime = 0;
     }
 
     private Ops getOpsRawLocked(int uid, String packageName, boolean edit,