Suppress all background-state services in user-forced app standby

Foreground services are treated as normal services when the user has
placed the app under FAS restrictions.  The API contract for the app
is unchanged -- for example, if the app calls startForegroundService()
in this state it will still ANR if it fails to call startForeground()
as promised.  All service starts are quietly suppressed unless the app
is showing foreground UI.

If an app is already running a foreground service when FAS is applied,
that service is taken out of the fg state and thereafter treated like an
ordinary background service in a background state:  after 1 minute, the
service is summarily stopped by the OS.

Bug: 73559697
Test: ApiDemos fg service suite
Test: atest CtsAppTestCases
Change-Id: Icc5fb180b90cb5d902e96aeb92a93f6daf00bd9b
diff --git a/services/core/java/com/android/server/AppStateTracker.java b/services/core/java/com/android/server/AppStateTracker.java
index 16be680..2affb74 100644
--- a/services/core/java/com/android/server/AppStateTracker.java
+++ b/services/core/java/com/android/server/AppStateTracker.java
@@ -266,6 +266,12 @@
                 // we need to deliver the allow-while-idle alarms for this uid, package
                 unblockAllUnrestrictedAlarms();
             }
+
+            if (!sender.isRunAnyInBackgroundAppOpsAllowed(uid, packageName)) {
+                Slog.v(TAG, "Package " + packageName + "/" + uid
+                        + " toggled into fg service restriction");
+                stopForegroundServicesForUidPackage(uid, packageName);
+            }
         }
 
         /**
@@ -359,6 +365,13 @@
         }
 
         /**
+         * Called when an app goes into forced app standby and its foreground
+         * services need to be removed from that state.
+         */
+        public void stopForegroundServicesForUidPackage(int uid, String packageName) {
+        }
+
+        /**
          * Called when the job restrictions for multiple UIDs might have changed, so the alarm
          * manager should re-evaluate all restrictions for all blocked jobs.
          */
@@ -1062,6 +1075,16 @@
     }
 
     /**
+     * @return whether foreground services should be suppressed in the background
+     * due to forced app standby for the given app
+     */
+    public boolean areForegroundServicesRestricted(int uid, @NonNull String packageName) {
+        synchronized (mLock) {
+            return isRunAnyRestrictedLocked(uid, packageName);
+        }
+    }
+
+    /**
      * @return whether force-app-standby is effective for a UID package-name.
      */
     private boolean isRestricted(int uid, @NonNull String packageName,