Revert "Ensure network connectivity on app start."

This reverts commit 27e693158398059d00ff20e60640cb105e255625.

Change-Id: I4c41ce7c1839d3b91931bc8a8f117f32bf6cd381
diff --git a/core/java/android/app/ActivityManagerInternal.java b/core/java/android/app/ActivityManagerInternal.java
index 4e34552..fa64a0f 100644
--- a/core/java/android/app/ActivityManagerInternal.java
+++ b/core/java/android/app/ActivityManagerInternal.java
@@ -22,7 +22,6 @@
 import android.content.IIntentSender;
 import android.content.Intent;
 import android.content.res.Configuration;
-import android.net.NetworkPolicyManager.UidStateWithSeqObserver;
 import android.os.Bundle;
 import android.os.IBinder;
 import android.service.voice.IVoiceInteractionSession;
@@ -234,16 +233,4 @@
      * @see android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY
      */
     public abstract void setHasOverlayUi(int pid, boolean hasOverlayUi);
-
-    /**
-     * Set observer which listens to uid state changes. Uid state change along with the sequence
-     * number associated with it needs to be passed to {@link UidStateWithSeqObserver}.
-     */
-    public abstract void setUidStateWithSeqObserver(UidStateWithSeqObserver observer);
-
-    /**
-     * Notifies that NetworkPolicyManagerService has updated the network policy rules for
-     * a specific {@param uid} and {@param procStateSeq}.
-     */
-    public abstract void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq);
 }
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index 77ed5f4..dffd81f 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -180,7 +180,6 @@
     public static final boolean DEBUG_CONFIGURATION = false;
     private static final boolean DEBUG_SERVICE = false;
     private static final boolean DEBUG_MEMORY_TRIM = false;
-    private static final boolean DEBUG_NETWORK = false;
     private static final boolean DEBUG_PROVIDER = false;
     private static final boolean DEBUG_ORDER = false;
     private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
@@ -203,55 +202,6 @@
     // Whether to invoke an activity callback after delivering new configuration.
     private static final boolean REPORT_TO_ACTIVITY = true;
 
-    /**
-     * This is the time main thread waits for the NetworkPolicyManagerService to notify
-     * that network is unrestricted. After this the app components will be launched anyway.
-     */
-    private long mWaitForNetworkTimeoutMs;
-
-    /**
-     * This is only for logging purposes. This will help us identify if the waiting for network
-     * is responsible for any lag that user might see.
-     */
-    private static final int WAIT_FOR_NETWORK_THRESHOLD_MS = 100; // 0.1 sec
-
-    /**
-     * State indicating that there is no need for any blocking for network.
-     */
-    public static final int NETWORK_STATE_NO_CHANGE = 0;
-
-    /**
-     * State indicating that main thread should wait for ActivityManagerService to notify
-     * before the app components are launched.
-     */
-    public static final int NETWORK_STATE_BLOCK = 1;
-
-    /**
-     * State indicating that any threads waiting for ActivityManagerService to notify should
-     * be unblocked.
-     */
-    public static final int NETWORK_STATE_UNBLOCK = 2;
-
-    /**
-     * Constant for indicating a invalid sequence number.
-     */
-    public static final long INVALID_PROC_STATE_SEQ = -1;
-
-    /**
-     * Current sequence number associated with the process state change.
-     */
-    @GuardedBy("mNetworkPolicyLock")
-    private long mCurProcStateSeq;
-
-    /**
-     * Indicates whether any component being launched should block for network before
-     * proceeding.
-     */
-    @GuardedBy("mNetworkPolicyLock")
-    private boolean mShouldBlockForNetwork;
-
-    private Object mNetworkPolicyLock = new Object();
-
     private ContextImpl mSystemContext;
 
     static volatile IPackageManager sPackageManager;
@@ -1356,18 +1306,6 @@
         }
 
         @Override
-        public void setBlockForNetworkState(int blockState, long targetProcStateSeq) {
-            synchronized (mNetworkPolicyLock) {
-                if (blockState == NETWORK_STATE_UNBLOCK) {
-                    unblockForNetworkAccessLN(targetProcStateSeq);
-                } else if (blockState == NETWORK_STATE_BLOCK) {
-                    mShouldBlockForNetwork = true;
-                }
-                mCurProcStateSeq = targetProcStateSeq;
-            }
-        }
-
-        @Override
         public void scheduleInstallProvider(ProviderInfo provider) {
             sendMessage(H.INSTALL_PROVIDER, provider);
         }
@@ -1450,13 +1388,6 @@
         public void handleTrustStorageUpdate() {
             NetworkSecurityPolicy.getInstance().handleTrustStorageUpdate();
         }
-
-        @Override
-        public void notifyNetworkStateUpdated(long curProcStateSeq) {
-            synchronized (mNetworkPolicyLock) {
-                unblockForNetworkAccessLN(curProcStateSeq);
-            }
-        }
     }
 
     private int getLifecycleSeq() {
@@ -2148,79 +2079,6 @@
         }
     }
 
-    void blockForNetworkAccessInForegroundService(long procStateSeq) {
-        synchronized (mNetworkPolicyLock) {
-            if (mCurProcStateSeq >= procStateSeq) {
-                if (mShouldBlockForNetwork) {
-                    blockForNetworkAccessLN();
-                }
-            } else {
-                mCurProcStateSeq = procStateSeq;
-                mShouldBlockForNetwork = true;
-                blockForNetworkAccessLN();
-            }
-        }
-    }
-
-    /**
-     * Block for unrestricted network. It will register a listener to AMS and wait for it to
-     * notify that network policy rules are updated. This method is called before relevant app
-     * components are launched.
-     */
-    private void blockForNetworkAccessLN() {
-        try {
-            if (ActivityManager.getService().registerNetworkRulesUpdateListener(
-                    mAppThread, mCurProcStateSeq)) {
-                try {
-                    Slog.d(TAG, "Uid: " + mBoundApplication.appInfo.uid
-                            + " seq: " + mCurProcStateSeq
-                            + ". Blocking for network. callers: " + Debug.getCallers(3));
-                    final long blockStartTime = SystemClock.elapsedRealtime();
-                    mNetworkPolicyLock.wait(mWaitForNetworkTimeoutMs);
-                    final long totalWaitTime = (SystemClock.elapsedRealtime() - blockStartTime);
-                    if (totalWaitTime >= mWaitForNetworkTimeoutMs) {
-                        Slog.wtf(TAG, "Timed out waiting for the network rules to get updated."
-                                + " Uid: " + mBoundApplication.appInfo.uid + " seq: "
-                                + mCurProcStateSeq);
-                    } else if (totalWaitTime >= WAIT_FOR_NETWORK_THRESHOLD_MS) {
-                        Slog.d(TAG, "Waited for time greater than threshold."
-                                + " Uid: " + mBoundApplication.appInfo.uid + " seq: "
-                                + mCurProcStateSeq);
-                    }
-                    if (DEBUG_NETWORK) {
-                        Slog.d(TAG, "Uid: " + mBoundApplication.appInfo.uid
-                                + " seq: " + mCurProcStateSeq
-                                + ". Time waited for network: " + totalWaitTime);
-                    }
-                } catch (InterruptedException ignored) {
-                }
-            }
-        } catch (RemoteException ignored) {
-        }
-    }
-
-    public void checkAndBlockForNetworkAccess() {
-        synchronized (mNetworkPolicyLock) {
-            if (mWaitForNetworkTimeoutMs > 0 && mShouldBlockForNetwork) {
-                blockForNetworkAccessLN();
-            }
-        }
-    }
-
-    /**
-     * Unblock the main thread if it is waiting for network.
-     */
-    private void unblockForNetworkAccessLN(long procStateSeq) {
-        if (mShouldBlockForNetwork && procStateSeq >= mCurProcStateSeq) {
-            if (DEBUG_NETWORK) {
-                Slog.d(TAG, "Unblocking threads waiting for network. uid: "
-                        + mBoundApplication.appInfo.uid + " procStateSeq: " + procStateSeq);
-            }
-            mNetworkPolicyLock.notifyAll();
-            mShouldBlockForNetwork = false;
-        }
-    }
-
     ActivityThread() {
         mResourcesManager = ResourcesManager.getInstance();
     }
@@ -2813,7 +2671,6 @@
                     activity.mIntent = customIntent;
                 }
                 r.lastNonConfigurationInstances = null;
-                checkAndBlockForNetworkAccess();
                 activity.mStartedActivity = false;
                 int theme = r.activityInfo.getThemeResource();
                 if (theme != 0) {
@@ -5493,9 +5350,6 @@
         View.mDebugViewAttributes =
                 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0;
 
-        mWaitForNetworkTimeoutMs = mCoreSettings.getLong(
-                Settings.Global.WAIT_FOR_NETWORK_TIMEOUT_MS);
-
         /**
          * For system applications on userdebug/eng builds, log stack
          * traces of disk and network access to dropbox for analysis.
diff --git a/core/java/android/app/IActivityManager.aidl b/core/java/android/app/IActivityManager.aidl
index 6719be4..585bd05 100644
--- a/core/java/android/app/IActivityManager.aidl
+++ b/core/java/android/app/IActivityManager.aidl
@@ -199,7 +199,7 @@
     int getRequestedOrientation(in IBinder token);
     void unbindFinished(in IBinder token, in Intent service, boolean doRebind);
     void setProcessForeground(in IBinder token, int pid, boolean isForeground);
-    long setServiceForeground(in ComponentName className, in IBinder token,
+    void setServiceForeground(in ComponentName className, in IBinder token,
             int id, in Notification notification, int flags);
     boolean moveActivityTaskToBack(in IBinder token, boolean nonRoot);
     void getMemoryInfo(out ActivityManager.MemoryInfo outInfo);
@@ -603,16 +603,6 @@
     ActivityManager.TaskSnapshot getTaskSnapshot(int taskId);
 
     void scheduleApplicationInfoChanged(in List<String> packageNames, int userId);
-     /**
-      * Registers a listener for network rules state. When the network policy rules in
-      * NetworkPolicyManagerService are updated, ActivityManagerService will notify these
-      * registered listeners.
-      *
-      * @param procStateSeq The sequence number for which the listener is interested in knowing
-      *                     the network policy rules state.
-      * @return true if the listener is registered, false otherwise.
-      */
-    boolean registerNetworkRulesUpdateListener(IApplicationThread listener, long procStateSeq);
 
     // WARNING: when these transactions are updated, check if they are any callers on the native
     // side. If so, make sure they are using the correct transaction ids and arguments.
diff --git a/core/java/android/app/IApplicationThread.aidl b/core/java/android/app/IApplicationThread.aidl
index 7378e2b..4fc6fb9 100644
--- a/core/java/android/app/IApplicationThread.aidl
+++ b/core/java/android/app/IApplicationThread.aidl
@@ -153,6 +153,4 @@
     void handleTrustStorageUpdate();
     void attachAgent(String path);
     void scheduleApplicationInfoChanged(in ApplicationInfo ai);
-    void setBlockForNetworkState(int blockState, long procStateSeq);
-    void notifyNetworkStateUpdated(long procStateSeq);
 }
diff --git a/core/java/android/app/Service.java b/core/java/android/app/Service.java
index 9cd048e..4fe4f98 100644
--- a/core/java/android/app/Service.java
+++ b/core/java/android/app/Service.java
@@ -683,28 +683,26 @@
      * flag if killing your service would be disruptive to the user, such as
      * if your service is performing background music playback, so the user
      * would notice if their music stopped playing.
-     *
+     * 
      * <p>If you need your application to run on platform versions prior to API
      * level 5, you can use the following model to call the the older setForeground()
      * or this modern method as appropriate:
-     *
+     * 
      * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/ForegroundService.java
      *   foreground_compatibility}
-     *
+     * 
      * @param id The identifier for this notification as per
      * {@link NotificationManager#notify(int, Notification)
      * NotificationManager.notify(int, Notification)}; must not be 0.
      * @param notification The Notification to be displayed.
-     *
+     * 
      * @see #stopForeground(boolean)
      */
     public final void startForeground(int id, Notification notification) {
         try {
-            final long procStateSeq = mActivityManager.setServiceForeground(
-                    new ComponentName(this, mClassName), mToken, id, notification, 0);
-            if (procStateSeq != ActivityThread.INVALID_PROC_STATE_SEQ && mThread != null) {
-                mThread.blockForNetworkAccessInForegroundService(procStateSeq);
-            }
+            mActivityManager.setServiceForeground(
+                    new ComponentName(this, mClassName), mToken, id,
+                    notification, 0);
         } catch (RemoteException ex) {
         }
     }
diff --git a/core/java/android/net/NetworkPolicyManager.java b/core/java/android/net/NetworkPolicyManager.java
index 4b184f1..1b715af 100644
--- a/core/java/android/net/NetworkPolicyManager.java
+++ b/core/java/android/net/NetworkPolicyManager.java
@@ -19,7 +19,6 @@
 import static android.content.pm.PackageManager.GET_SIGNATURES;
 import static android.net.NetworkPolicy.CYCLE_NONE;
 
-import android.app.ActivityManager;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
@@ -66,8 +65,6 @@
      *
      * See network-policy-restrictions.md for more info.
      */
-    /** Not a valid rule */
-    public static final int RULE_INVALID = -1;
     /** No specific rule was set */
     public static final int RULE_NONE = 0;
     /** Allow traffic on metered networks. */
@@ -363,8 +360,6 @@
         final StringBuilder string = new StringBuilder().append(uidRules).append(" (");
         if (uidRules == RULE_NONE) {
             string.append("NONE");
-        } else if (uidRules == RULE_INVALID) {
-            string.append("INVALID");
         } else {
             string.append(DebugUtils.flagsToString(NetworkPolicyManager.class, "RULE_", uidRules));
         }
@@ -386,25 +381,4 @@
         string.append(")");
         return string.toString();
     }
-
-    /**
-     * @hide
-     */
-    public static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
-        return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
-    }
-
-    /**
-     * @hide
-     */
-    public static boolean isProcStateAllowedWhileRestrictBackgroundOn(int procState) {
-        return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
-    }
-
-    /**
-     * @hide
-     */
-    public interface UidStateWithSeqObserver {
-        void onUidStateChangedWithSeq(int uid, int procState, long seq);
-    }
 }
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index e0ac0ea..1655847 100755
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -9557,16 +9557,6 @@
         public static final String RETAIL_DEMO_MODE_CONSTANTS = "retail_demo_mode_constants";
 
         /**
-         * When blocked for the network policy rules to get updated, the maximum time that the
-         * {@link ActivityThread} have to wait before unblocking.
-         *
-         * Type: long
-         *
-         * @hide
-         */
-        public static final String WAIT_FOR_NETWORK_TIMEOUT_MS = "wait_for_network_timeout_ms";
-
-        /**
          * The reason for the settings database being downgraded. This is only for
          * troubleshooting purposes and its value should not be interpreted in any way.
          *
diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java
index cec5800..2bc131f 100644
--- a/services/core/java/com/android/server/am/ActiveServices.java
+++ b/services/core/java/com/android/server/am/ActiveServices.java
@@ -703,27 +703,21 @@
         return false;
     }
 
-    public long setServiceForegroundLocked(ComponentName className, IBinder token,
+    public void setServiceForegroundLocked(ComponentName className, IBinder token,
             int id, Notification notification, int flags) {
         final int userId = UserHandle.getCallingUserId();
         final long origId = Binder.clearCallingIdentity();
         try {
             ServiceRecord r = findServiceLocked(className, token, userId);
             if (r != null) {
-                return setServiceForegroundInnerLocked(r, id, notification, flags);
+                setServiceForegroundInnerLocked(r, id, notification, flags);
             }
-            return ActivityThread.INVALID_PROC_STATE_SEQ;
         } finally {
             Binder.restoreCallingIdentity(origId);
         }
     }
 
-    /**
-     * @return current process state sequence number {@link UidRecord#curProcStateSeq} corresponding
-     *         to the ServiceRecord {@param r} if the calling service has to block until the
-     *         network rules are udpated, Otherwise {@link ActivityThread#INVALID_PROC_STATE_SEQ}.
-     */
-    private long setServiceForegroundInnerLocked(ServiceRecord r, int id,
+    private void setServiceForegroundInnerLocked(ServiceRecord r, int id,
             Notification notification, int flags) {
         if (id != 0) {
             if (notification == null) {
@@ -742,7 +736,7 @@
                         Slog.w(TAG, "Instant app " + r.appInfo.packageName
                                 + " does not have permission to create foreground services"
                                 + ", ignoring.");
-                        return ActivityThread.INVALID_PROC_STATE_SEQ;
+                        return;
                     case AppOpsManager.MODE_ERRORED:
                         throw new SecurityException("Instant app " + r.appInfo.packageName
                                 + " does not have permission to create foreground services");
@@ -770,18 +764,12 @@
             r.foregroundNoti = notification;
             r.isForeground = true;
             r.postNotification();
-            long procStateSeqToReturn = ActivityThread.INVALID_PROC_STATE_SEQ;
             if (r.app != null) {
                 updateServiceForegroundLocked(r.app, true);
-                if (r.app.uidRecord != null &&
-                        r.app.uidRecord.blockState == ActivityThread.NETWORK_STATE_BLOCK) {
-                    procStateSeqToReturn = r.app.uidRecord.curProcStateSeq;
-                }
             }
             getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
             mAm.notifyPackageUse(r.serviceInfo.packageName,
                                  PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
-            return procStateSeqToReturn;
         } else {
             if (r.isForeground) {
                 r.isForeground = false;
@@ -802,7 +790,6 @@
                 }
             }
         }
-        return ActivityThread.INVALID_PROC_STATE_SEQ;
     }
 
     private void cancelForegroudNotificationLocked(ServiceRecord r) {
diff --git a/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java b/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java
index 8ed95ee..88e0d03 100644
--- a/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java
+++ b/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java
@@ -63,7 +63,6 @@
     static final boolean DEBUG_LOCKTASK = DEBUG_ALL || false;
     static final boolean DEBUG_LRU = DEBUG_ALL || false;
     static final boolean DEBUG_MU = DEBUG_ALL || false;
-    static final boolean DEBUG_NETWORK = DEBUG_ALL || false;
     static final boolean DEBUG_OOM_ADJ = DEBUG_ALL || false;
     static final boolean DEBUG_PAUSE = DEBUG_ALL || false;
     static final boolean DEBUG_POWER = DEBUG_ALL || false;
@@ -108,7 +107,6 @@
     static final String POSTFIX_LOCKTASK = (APPEND_CATEGORY_NAME) ? "_LockTask" : "";
     static final String POSTFIX_LRU = (APPEND_CATEGORY_NAME) ? "_LRU" : "";
     static final String POSTFIX_MU = "_MU";
-    static final String POSTFIX_NETWORK = "_Network";
     static final String POSTFIX_OOM_ADJ = (APPEND_CATEGORY_NAME) ? "_OomAdj" : "";
     static final String POSTFIX_PAUSE = (APPEND_CATEGORY_NAME) ? "_Pause" : "";
     static final String POSTFIX_POWER = (APPEND_CATEGORY_NAME) ? "_Power" : "";
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 072b0ea..1375c01 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -42,9 +42,6 @@
 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
 import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
-import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
-import static android.net.NetworkPolicyManager.isProcStateAllowedWhileRestrictBackgroundOn;
-import static android.net.NetworkPolicyManager.UidStateWithSeqObserver;
 import static android.os.Build.VERSION_CODES.N;
 import static android.os.Process.PROC_CHAR;
 import static android.os.Process.PROC_OUT_LONG;
@@ -79,7 +76,6 @@
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LRU;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
-import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_NETWORK;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER;
@@ -109,7 +105,6 @@
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKTASK;
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LRU;
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
-import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_NETWORK;
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_OOM_ADJ;
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_POWER;
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESSES;
@@ -358,7 +353,6 @@
 import com.android.server.Watchdog;
 import com.android.server.am.ActivityStack.ActivityState;
 import com.android.server.firewall.IntentFirewall;
-import com.android.server.net.NetworkPolicyManagerService;
 import com.android.server.pm.Installer;
 import com.android.server.pm.Installer.InstallerException;
 import com.android.server.statusbar.StatusBarManagerInternal;
@@ -415,7 +409,6 @@
     private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
     private static final String TAG_LRU = TAG + POSTFIX_LRU;
     private static final String TAG_MU = TAG + POSTFIX_MU;
-    private static final String TAG_NETWORK = TAG + POSTFIX_NETWORK;
     private static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ;
     private static final String TAG_POWER = TAG + POSTFIX_POWER;
     private static final String TAG_PROCESS_OBSERVERS = TAG + POSTFIX_PROCESS_OBSERVERS;
@@ -602,8 +595,6 @@
     BroadcastStats mLastBroadcastStats;
     BroadcastStats mCurBroadcastStats;
 
-    private UidStateWithSeqObserver mUidStateWithSeqObserver;
-
     BroadcastQueue broadcastQueueForIntent(Intent intent) {
         final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
         if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST,
@@ -4220,25 +4211,6 @@
                     "*** Delivering " + N + " uid changes");
         }
 
-        if (mUidStateWithSeqObserver != null) {
-            final int registeredCallbackCount = mUidObservers.getRegisteredCallbackCount();
-            for (int i = 0; i < N; ++i) {
-                final UidRecord.ChangeItem item = mActiveUidChanges[i];
-                if (item.change == UidRecord.CHANGE_PROCSTATE) {
-                    mUidStateWithSeqObserver.onUidStateChangedWithSeq(
-                            item.uid, item.processState, item.procStateSeq);
-                    if (VALIDATE_UID_STATES && registeredCallbackCount == 0) {
-                        UidRecord validateUid = mValidateUids.get(item.uid);
-                        if (validateUid == null) {
-                            validateUid = new UidRecord(item.uid);
-                            mValidateUids.put(item.uid, validateUid);
-                        }
-                        validateUid.curProcState = validateUid.setProcState = item.processState;
-                    }
-                }
-            }
-        }
-
         int i = mUidObservers.beginBroadcast();
         while (i > 0) {
             i--;
@@ -17601,16 +17573,11 @@
         }
     }
 
-    /**
-     * Returns sequence number associated with the current process state change if the service
-     * coming to the foreground needs to block for network before proceeding, otherwise
-     * {@link ActivityThread#INVALID_PROC_STATE_SEQ}.
-     */
     @Override
-    public long setServiceForeground(ComponentName className, IBinder token,
+    public void setServiceForeground(ComponentName className, IBinder token,
             int id, Notification notification, int flags) {
         synchronized(this) {
-            return mServices.setServiceForegroundLocked(className, token, id, notification, flags);
+            mServices.setServiceForegroundLocked(className, token, id, notification, flags);
         }
     }
 
@@ -21371,7 +21338,6 @@
         pendingChange.processState = uidRec != null
                 ? uidRec.setProcState : ActivityManager.PROCESS_STATE_NONEXISTENT;
         pendingChange.ephemeral = uidRec.ephemeral;
-        pendingChange.procStateSeq = uidRec.curProcStateSeq;
 
         // Directly update the power manager, since we sit on top of it and it is critical
         // it be kept in sync (so wake locks will be held as soon as appropriate).
@@ -21745,34 +21711,6 @@
             }
         }
 
-        for (int i = mActiveUids.size() - 1; i >= 0; --i) {
-            final UidRecord uidRec = mActiveUids.valueAt(i);
-            uidRec.shouldNotifyAppThreads = false;
-            if (uidRec.curProcState == uidRec.setProcState) {
-                continue;
-            }
-            final int newBlockState = getUidRecordBlockState(uidRec);
-            // Sequence no. associated with process state change will only be updated if the
-            // process is coming from background to foreground or vice versa.
-            if (newBlockState != uidRec.blockState) {
-                uidRec.blockState = newBlockState;
-                uidRec.curProcStateSeq++;
-                uidRec.appThreadListeners = null;
-                uidRec.shouldNotifyAppThreads = true;
-            }
-        }
-
-        for (int i = mLruProcesses.size() - 1; i >= 0; --i) {
-            final ProcessRecord app = mLruProcesses.get(i);
-            if (!app.killedByAm && app.thread != null && app.uidRecord.shouldNotifyAppThreads) {
-                try {
-                    app.thread.setBlockForNetworkState(app.uidRecord.blockState,
-                            app.uidRecord.curProcStateSeq);
-                } catch (RemoteException ignored) {
-                }
-            }
-        }
-
         mNumServiceProcs = mNewNumServiceProcs;
 
         // Now determine the memory trimming level of background processes.
@@ -22974,131 +22912,6 @@
                 updateOomAdjLocked(pr);
             }
         }
-
-        @Override
-        public void setUidStateWithSeqObserver(UidStateWithSeqObserver observer) {
-            synchronized (ActivityManagerService.this) {
-                mUidStateWithSeqObserver = observer;
-            }
-        }
-
-        @Override
-        public void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq) {
-            if (DEBUG_NETWORK) {
-                Slog.d(TAG_NETWORK, "Got update from NPMS uid: " + uid + " seq: " + procStateSeq);
-            }
-            synchronized (ActivityManagerService.this) {
-                final UidRecord record = mActiveUids.get(uid);
-                if (record == null) {
-                    if (DEBUG_NETWORK) {
-                        Slog.d(TAG_NETWORK, "No active uidRecord for uid: " + uid
-                                + "seq: " + procStateSeq);
-                    }
-                    return;
-                }
-                record.lastProcStateSeqWithUpdatedNetworkState = procStateSeq;
-                if (record.curProcStateSeq > procStateSeq) {
-                    if (DEBUG_NETWORK) {
-                        Slog.d(TAG_NETWORK, "Since the current procStateSeq is greater, the "
-                                + "listeners would already be notified when it is incremented.");
-                    }
-                    return;
-                }
-
-                if (record.appThreadListeners == null) {
-                    if (DEBUG_NETWORK) {
-                        Slog.d(TAG_NETWORK, "No app thread listeners for uid: " + uid
-                                + "seq: " + procStateSeq);
-                    }
-                    return;
-                }
-                for (int i = record.appThreadListeners.beginBroadcast() - 1; i >= 0; i--) {
-                    final IApplicationThread listener =
-                            record.appThreadListeners.getBroadcastItem(i);
-                    try {
-                        if (listener != null) {
-                            listener.notifyNetworkStateUpdated(procStateSeq);
-                        }
-                    } catch (RemoteException ignored) {
-                    }
-                }
-                record.appThreadListeners.finishBroadcast();
-                record.appThreadListeners = null;
-            }
-        }
-    }
-
-    @Override
-    public boolean registerNetworkRulesUpdateListener(IApplicationThread listener,
-            long procStateSeq) {
-        synchronized (this) {
-            final int uid = Binder.getCallingUid();
-            final UidRecord record = mActiveUids.get(uid);
-            if (record.lastProcStateSeqWithUpdatedNetworkState >= procStateSeq) {
-                if (DEBUG_NETWORK) {
-                    Slog.v(TAG_NETWORK, "Network state is already updated for seq: " + procStateSeq
-                            + ". No need to register listener for uid: " + uid);
-                }
-                return false;
-            }
-            if (record.curProcStateSeq > procStateSeq) {
-                if (DEBUG_NETWORK) {
-                    Slog.v(TAG_NETWORK, "Since the current procState is greater, there is no need "
-                            + " to register listeners for older seq numbers");
-                }
-            }
-            if (record.appThreadListeners == null) {
-                record.appThreadListeners = new RemoteCallbackList<>();
-            }
-            record.appThreadListeners.register(listener);
-            if (DEBUG_NETWORK) {
-                Slog.v(TAG_NETWORK, "Registered listener for uid: " + uid + " seq: " + procStateSeq);
-            }
-            return true;
-        }
-    }
-
-    private int getUidRecordBlockState(UidRecord uidRec) {
-        final boolean curStateAllowedWhileRestrictBackgroundOn
-                = isProcStateAllowedWhileRestrictBackgroundOn(uidRec.curProcState);
-        final boolean curStateAllowedWhileIdleOrPowerSaveMode
-                = isProcStateAllowedWhileIdleOrPowerSaveMode(uidRec.curProcState);
-
-        if (uidRec.setProcState == ActivityManager.PROCESS_STATE_UNKNOWN) {
-            if (uidRec.curProcState != ActivityManager.PROCESS_STATE_UNKNOWN &&
-                    (curStateAllowedWhileIdleOrPowerSaveMode
-                            || curStateAllowedWhileRestrictBackgroundOn)) {
-                return ActivityThread.NETWORK_STATE_BLOCK;
-            }
-            return ActivityThread.NETWORK_STATE_NO_CHANGE;
-        }
-
-        final boolean prevStateAllowedWhileRestrictBackgroundOn
-                = isProcStateAllowedWhileRestrictBackgroundOn(uidRec.setProcState);
-        final boolean prevStateAllowedWhileIdleOrPowerSaveMode
-                = isProcStateAllowedWhileIdleOrPowerSaveMode(uidRec.setProcState);
-
-        if (prevStateAllowedWhileIdleOrPowerSaveMode == curStateAllowedWhileIdleOrPowerSaveMode &&
-                prevStateAllowedWhileRestrictBackgroundOn ==
-                        curStateAllowedWhileRestrictBackgroundOn) {
-            return uidRec.blockState;
-        }
-
-        if (!prevStateAllowedWhileIdleOrPowerSaveMode && curStateAllowedWhileIdleOrPowerSaveMode) {
-            return ActivityThread.NETWORK_STATE_BLOCK;
-        } else if (!prevStateAllowedWhileRestrictBackgroundOn
-                && curStateAllowedWhileRestrictBackgroundOn) {
-            return ActivityThread.NETWORK_STATE_BLOCK;
-        }
-
-        if (prevStateAllowedWhileIdleOrPowerSaveMode && !curStateAllowedWhileIdleOrPowerSaveMode) {
-            return ActivityThread.NETWORK_STATE_UNBLOCK;
-        } else if (prevStateAllowedWhileRestrictBackgroundOn &&
-                !curStateAllowedWhileRestrictBackgroundOn) {
-            return ActivityThread.NETWORK_STATE_UNBLOCK;
-        }
-
-        return uidRec.blockState;
     }
 
     private final class SleepTokenImpl extends SleepToken {
diff --git a/services/core/java/com/android/server/am/CoreSettingsObserver.java b/services/core/java/com/android/server/am/CoreSettingsObserver.java
index 9b459d1..73a17c6 100644
--- a/services/core/java/com/android/server/am/CoreSettingsObserver.java
+++ b/services/core/java/com/android/server/am/CoreSettingsObserver.java
@@ -49,7 +49,6 @@
         // add other system settings here...
 
         sGlobalSettingToTypeMap.put(Settings.Global.DEBUG_VIEW_ATTRIBUTES, int.class);
-        sGlobalSettingToTypeMap.put(Settings.Global.WAIT_FOR_NETWORK_TIMEOUT_MS, long.class);
         // add other global settings here...
     }
 
@@ -57,8 +56,6 @@
 
     private final ActivityManagerService mActivityManagerService;
 
-    private static final long WAIT_FOR_NETWORK_TIMEOUT_DEFAULT_MS = 2000; // 2 sec
-
     public CoreSettingsObserver(ActivityManagerService activityManagerService) {
         super(activityManagerService.mHandler);
         mActivityManagerService = activityManagerService;
@@ -146,13 +143,7 @@
                 } else if (map == sSystemSettingToTypeMap) {
                     value = Settings.System.getLong(context.getContentResolver(), setting, 0);
                 } else {
-                    // TODO: remove this conditional and set the default in settings provider.
-                    if (Settings.Global.WAIT_FOR_NETWORK_TIMEOUT_MS.equals(setting)) {
-                        value = Settings.Global.getLong(context.getContentResolver(), setting,
-                                WAIT_FOR_NETWORK_TIMEOUT_DEFAULT_MS);
-                    } else {
-                        value = Settings.Global.getLong(context.getContentResolver(), setting, 0);
-                    }
+                    value = Settings.Global.getLong(context.getContentResolver(), setting, 0);
                 }
                 snapshot.putLong(setting, value);
             }
diff --git a/services/core/java/com/android/server/am/UidRecord.java b/services/core/java/com/android/server/am/UidRecord.java
index 1e16bc9..302f628 100644
--- a/services/core/java/com/android/server/am/UidRecord.java
+++ b/services/core/java/com/android/server/am/UidRecord.java
@@ -17,12 +17,8 @@
 package com.android.server.am;
 
 import android.app.ActivityManager;
-import android.app.ActivityThread;
-import android.app.IApplicationThread;
-import android.os.RemoteCallbackList;
 import android.os.SystemClock;
 import android.os.UserHandle;
-import android.util.DebugUtils;
 import android.util.TimeUtils;
 
 /**
@@ -38,27 +34,6 @@
     boolean setWhitelist;
     boolean idle;
     int numProcs;
-    /**
-     * Seq no. associated with the current process state change (from background to foreground or
-     * vice versa).
-     */
-    long curProcStateSeq;
-    /**
-     * Latest seq number for which NetworkPolicyManagerService notified ActivityManagerService that
-     * network policy rules are updated.
-     */
-    long lastProcStateSeqWithUpdatedNetworkState;
-    /**
-     * Current block state indicating whether components in the process corresponding to this
-     * uidRecord needs to block for network or unblock or if there is no change.
-     * value will be one of {@link ActivityThread#NETWORK_STATE_BLOCK},
-     * {@link ActivityThread#NETWORK_STATE_UNBLOCK}, {@link ActivityThread#NETWORK_STATE_NO_CHANGE}.
-     */
-    int blockState;
-    /** Indicates whether app threads need be notified of the current blockState change. */
-    boolean shouldNotifyAppThreads;
-    /** Listeners waiting for the network policy rules to get updated. */
-    RemoteCallbackList<IApplicationThread> appThreadListeners;
 
     static final int CHANGE_PROCSTATE = 0;
     static final int CHANGE_GONE = 1;
@@ -72,7 +47,6 @@
         int change;
         int processState;
         boolean ephemeral;
-        long procStateSeq;
     }
 
     ChangeItem pendingChange;
@@ -109,14 +83,6 @@
         }
         sb.append(" procs:");
         sb.append(numProcs);
-        sb.append(" procStateSeq:");
-        sb.append(curProcStateSeq);
-        sb.append(" lastProcStateSeqWithUpdatedNetworkState:");
-        sb.append(lastProcStateSeqWithUpdatedNetworkState);
-        sb.append(" blockState:");
-        sb.append(DebugUtils.valueToString(ActivityThread.class, "NETWORK_STATE_", blockState));
-        sb.append(" shouldNotifyAppThreads:");
-        sb.append(shouldNotifyAppThreads);
         sb.append("}");
         return sb.toString();
     }
diff --git a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
index 91c9316..ac3a025 100644
--- a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
+++ b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
@@ -23,7 +23,6 @@
 import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
 import static android.Manifest.permission.READ_PHONE_STATE;
 import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
-import static android.app.ActivityThread.INVALID_PROC_STATE_SEQ;
 import static android.content.Intent.ACTION_PACKAGE_ADDED;
 import static android.content.Intent.ACTION_UID_REMOVED;
 import static android.content.Intent.ACTION_USER_ADDED;
@@ -54,15 +53,11 @@
 import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
 import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
 import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
-import static android.net.NetworkPolicyManager.RULE_INVALID;
 import static android.net.NetworkPolicyManager.RULE_NONE;
 import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
 import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
 import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
-import static android.net.NetworkPolicyManager.UidStateWithSeqObserver;
 import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
-import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
-import static android.net.NetworkPolicyManager.isProcStateAllowedWhileRestrictBackgroundOn;
 import static android.net.NetworkPolicyManager.uidPoliciesToString;
 import static android.net.NetworkPolicyManager.uidRulesToString;
 import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
@@ -99,7 +94,6 @@
 import android.annotation.IntDef;
 import android.annotation.Nullable;
 import android.app.ActivityManager;
-import android.app.ActivityManagerInternal;
 import android.app.AppGlobals;
 import android.app.AppOpsManager;
 import android.app.IActivityManager;
@@ -129,7 +123,6 @@
 import android.net.NetworkIdentity;
 import android.net.NetworkInfo;
 import android.net.NetworkPolicy;
-import android.net.NetworkPolicyManager;
 import android.net.NetworkQuotaInfo;
 import android.net.NetworkState;
 import android.net.NetworkTemplate;
@@ -137,7 +130,6 @@
 import android.net.wifi.WifiInfo;
 import android.net.wifi.WifiManager;
 import android.os.Binder;
-import android.os.Debug;
 import android.os.Environment;
 import android.os.Handler;
 import android.os.HandlerThread;
@@ -169,10 +161,8 @@
 import android.util.NtpTrustedTime;
 import android.util.Pair;
 import android.util.Slog;
-import android.util.SparseArray;
 import android.util.SparseBooleanArray;
 import android.util.SparseIntArray;
-import android.util.SparseLongArray;
 import android.util.TrustedTime;
 import android.util.Xml;
 
@@ -220,16 +210,14 @@
  * enforcement.
  *
  * <p>
- * This class uses 4 locks to synchronize state:
+ * This class uses 2-3 locks to synchronize state:
  * <ul>
  * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
  * rules).
  * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
  * as network policies).
- * <li>{@code mDispatchedThirdLock}: used to guard state related to process state sequence numbers
- * of uids which are currently blocked waiting for network.
- * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that both locks
- * {@code mUidRulesFirstLock} and {@code mNetworkPoliciesSecondLock} must be held.
+ * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
+ * must be held.
  * </ul>
  *
  * <p>
@@ -237,11 +225,8 @@
  * <ul>
  * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
  * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
- * <li>{@code DL()}: require the "Dispatched" lock ({@code mDispatchedThirdLock}).
- * <li>{@code AL()}: require both locks {@code mUidRulesFirstLock} and
- * {@code mNetworkPoliciesSecondLock}.
- * When multiple locks are needed, they must be obtained in order ({@code mUidRulesFirstLock}
- * first, then {@code mNetworkPoliciesSecondLock}, then {@code mDispatchedThirdLock}, etc..
+ * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
+ * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
  * </ul>
  */
 public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
@@ -328,27 +313,6 @@
     // See main javadoc for instructions on how to use these locks.
     final Object mUidRulesFirstLock = new Object();
     final Object mNetworkPoliciesSecondLock = new Object();
-    final Object mDispatchedThirdLock = new Object();
-
-    @GuardedBy("mDispatchedThirdLock")
-    private final SparseLongArray mLastHandledProcStateSeq = new SparseLongArray();
-
-    /**
-     * Used for tracking whether the updated uid and firewall rules have been dispatched to
-     * ConnectivityService and NetworkManagementService respectively.
-     *
-     * SparseIntArray: uid -> dispatch flags (one or more combinations of {@link #FLAG_NONE},
-     * {@link #FLAG_UID_RULES_DISPATCHED}, {@link #FLAG_FIREWALL_RULES_DISPATCHED} and
-     * {@link #FLAG_ALL_RULES_DISPATCHED}).
-     */
-    @GuardedBy("mDispatchedThirdLock")
-    private final SparseIntArray mDispatchFlagsForCurProcStateSeq = new SparseIntArray();
-
-    private final int FLAG_NONE = 0;
-    private final int FLAG_UID_RULES_DISPATCHED = 1 << 0;
-    private final int FLAG_FIREWALL_RULES_DISPATCHED = 1 << 1;
-    private final int FLAG_ALL_RULES_DISPATCHED =
-            (FLAG_UID_RULES_DISPATCHED | FLAG_FIREWALL_RULES_DISPATCHED);
 
     @GuardedBy("allLocks") volatile boolean mSystemReady;
 
@@ -443,8 +407,6 @@
 
     private final IPackageManager mIPm;
 
-    private ActivityManagerInternal mActivityManagerInternal;
-
 
     // TODO: keep whitelist of system-critical services that should never have
     // rules enforced, such as system, phone, and radio UIDs.
@@ -655,16 +617,13 @@
 
             try {
                 mActivityManager.registerUidObserver(mUidObserver,
-                        ActivityManager.UID_OBSERVER_GONE,
+                        ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
                         ActivityManager.PROCESS_STATE_UNKNOWN, null);
                 mNetworkManager.registerObserver(mAlertObserver);
             } catch (RemoteException e) {
                 // ignored; both services live in system_server
             }
 
-            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
-            mActivityManagerInternal.setUidStateWithSeqObserver(mUidStateWithSeqObserver);
-
             // listen for changes to power save whitelist
             final IntentFilter whitelistFilter = new IntentFilter(
                     PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
@@ -746,24 +705,17 @@
         }
     }
 
-    final private UidStateWithSeqObserver mUidStateWithSeqObserver = new UidStateWithSeqObserver() {
-        @Override
-        public void onUidStateChangedWithSeq(int uid, int procState, long procStateSeq) {
+    final private IUidObserver mUidObserver = new IUidObserver.Stub() {
+        @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
             Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
             try {
-                final long effectiveProcStateSeq = getEffectiveProcStateSeq(uid, procStateSeq);
                 synchronized (mUidRulesFirstLock) {
-                    updateUidStateUL(uid, procState, effectiveProcStateSeq);
+                    updateUidStateUL(uid, procState);
                 }
             } finally {
                 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
             }
         }
-    };
-
-    final private IUidObserver mUidObserver = new IUidObserver.Stub() {
-        @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
-        }
 
         @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
             synchronized (mUidRulesFirstLock) {
@@ -1890,7 +1842,7 @@
         }
 
         // uid policy changed, recompute rules and persist policy.
-        updateRulesForDataUsageRestrictionsUL(uid, true);
+        updateRulesForDataUsageRestrictionsUL(uid);
         if (persist) {
             synchronized (mNetworkPoliciesSecondLock) {
                 writePolicyAL();
@@ -2489,7 +2441,7 @@
 
     private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
         final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
-        return isProcStateAllowedWhileRestrictBackgroundOn(procState);
+        return isProcStateAllowedWhileOnRestrictBackground(procState);
     }
 
     private boolean isUidForegroundOnRestrictPowerUL(int uid) {
@@ -2507,50 +2459,26 @@
      * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
      * {@link #updateRulesForPowerRestrictionsUL(int)}
      */
-    private void updateUidStateUL(int uid, int uidState, long procStateSeq) {
+    private void updateUidStateUL(int uid, int uidState) {
         Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
         try {
             final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
             if (oldUidState != uidState) {
                 // state changed, push updated rules
                 mUidState.put(uid, uidState);
-                if (procStateSeq != INVALID_PROC_STATE_SEQ) {
-                    int updatedUidRules = RULE_INVALID;
-                    ReturnStatus status = updateRestrictBackgroundRulesOnUidStatusChangedUL(
-                            uid, oldUidState, uidState, false);
-                    if (status != null && status.mNeedToNotify) {
-                        updatedUidRules = status.mNewUidRules;
+                updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
+                if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
+                        != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
+                    if (isUidIdle(uid)) {
+                        updateRuleForAppIdleUL(uid);
                     }
-                    final boolean procStateChangedAllowedWhileIdleOrPowerSaveMode =
-                            isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
-                                    != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState);
-                    if (procStateChangedAllowedWhileIdleOrPowerSaveMode) {
-                        status = updateRulesForPowerRestrictionsUL(uid, false);
-                        if (status != null && status.mNeedToNotify) {
-                            updatedUidRules = status.mNewUidRules;
-                        }
+                    if (mDeviceIdleMode) {
+                        updateRuleForDeviceIdleUL(uid);
                     }
-                    // TODO: We can avoid this if the rules are not changed. But since dispatching
-                    // to ConnectivityService is currently asynchronous, we need this to make sure
-                    // any previous the msg_rules_changes have been handled. Optimize this once
-                    // dispatching from NPMS to ConnectivityService is made synchronous.
-                    mHandler.obtainMessage(MSG_RULES_CHANGED, uid, updatedUidRules,
-                            procStateSeq).sendToTarget();
-                    if (procStateChangedAllowedWhileIdleOrPowerSaveMode) {
-                        if (isUidIdle(uid)) {
-                            updateRuleForAppIdleUL(uid);
-                        }
-                        if (mDeviceIdleMode) {
-                            updateRuleForDeviceIdleUL(uid);
-                        }
-                        if (mRestrictPower) {
-                            updateRuleForRestrictPowerUL(uid);
-                        }
+                    if (mRestrictPower) {
+                        updateRuleForRestrictPowerUL(uid);
                     }
-                    synchronized (mDispatchedThirdLock) {
-                        setDispatchedFlagDL(uid, procStateSeq, FLAG_FIREWALL_RULES_DISPATCHED);
-                        checkAndNotifyDL(uid, procStateSeq);
-                    }
+                    updateRulesForPowerRestrictionsUL(uid);
                 }
                 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
             }
@@ -2559,61 +2487,6 @@
         }
     }
 
-    /**
-     * Returns {@link android.app.ActivityThread#INVALID_PROC_STATE_SEQ} if acting on
-     * {@param procStateSeq} leads to an invalid state, otherwise update global state and return
-     * {@param procStateSeq}.
-     */
-    private long getEffectiveProcStateSeq(int uid, long procStateSeq) {
-        synchronized (mDispatchedThirdLock) {
-            final long lastHandledProcStateSeq = mLastHandledProcStateSeq.get(uid);
-            if (procStateSeq < lastHandledProcStateSeq) {
-                Slog.wtf(TAG, "procStateSeq from AMS should never go down, procStateSeq: "
-                        + procStateSeq + " lastHandledProcStateSeq: " + lastHandledProcStateSeq
-                        + " uid: " + uid);
-                return INVALID_PROC_STATE_SEQ;
-            }
-            if (procStateSeq == lastHandledProcStateSeq) {
-                if (LOGD) {
-                    Slog.d(TAG, "procStateSeq: " + procStateSeq + " is not changed, so process is "
-                            + "not jumping from background to foreground or vice versa. "
-                            + "uid: " + uid);
-                }
-                return INVALID_PROC_STATE_SEQ;
-            }
-            mLastHandledProcStateSeq.put(uid, procStateSeq);
-            mDispatchFlagsForCurProcStateSeq.put(uid, 0);
-            return procStateSeq;
-        }
-    }
-
-    /**
-     * Update dispatch flags to include {@param flag}.
-     */
-    private void setDispatchedFlagDL(int uid, long procStateSeq, int flag) {
-        int dispatchedFlag = mDispatchFlagsForCurProcStateSeq.get(uid);
-        dispatchedFlag |= flag;
-        mDispatchFlagsForCurProcStateSeq.put(uid, dispatchedFlag);
-    }
-
-    /**
-     * Check whether uid and firewall rules are dispatched to ConnectivityService and
-     * NetworkManagementService respectively, if so notify ActivityManagerService that network
-     * rules are updated.
-     */
-    private void checkAndNotifyDL(int uid, long procStateSeq) {
-        synchronized (mDispatchedThirdLock) {
-            final int dispatchedFlags = mDispatchFlagsForCurProcStateSeq.get(uid);
-            if (dispatchedFlags == FLAG_ALL_RULES_DISPATCHED) {
-                if (LOGD) {
-                    Slog.d(TAG, "Notifying AMS that network rules are updated for uid: " + uid
-                            + " seq: " + procStateSeq + " callers: " + Debug.getCallers(3));
-                }
-                mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
-            }
-        }
-    }
-
     private void removeUidStateUL(int uid) {
         final int index = mUidState.indexOfKey(uid);
         if (index >= 0) {
@@ -2621,21 +2494,17 @@
             mUidState.removeAt(index);
             if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
                 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
-                        ActivityManager.PROCESS_STATE_CACHED_EMPTY, true);
+                        ActivityManager.PROCESS_STATE_CACHED_EMPTY);
                 if (mDeviceIdleMode) {
                     updateRuleForDeviceIdleUL(uid);
                 }
                 if (mRestrictPower) {
                     updateRuleForRestrictPowerUL(uid);
                 }
-                updateRulesForPowerRestrictionsUL(uid, true);
+                updateRulesForPowerRestrictionsUL(uid);
                 updateNetworkStats(uid, false);
             }
         }
-        synchronized (mDispatchedThirdLock) {
-            mLastHandledProcStateSeq.delete(uid);
-            mDispatchFlagsForCurProcStateSeq.delete(uid);
-        }
     }
 
     // adjust stats accounting based on foreground status
@@ -2647,16 +2516,23 @@
         }
     }
 
-    private ReturnStatus updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
-            int newUidState, boolean notify) {
+    private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
+            int newUidState) {
         final boolean oldForeground =
-                isProcStateAllowedWhileRestrictBackgroundOn(oldUidState);
+                isProcStateAllowedWhileOnRestrictBackground(oldUidState);
         final boolean newForeground =
-                isProcStateAllowedWhileRestrictBackgroundOn(newUidState);
+                isProcStateAllowedWhileOnRestrictBackground(newUidState);
         if (oldForeground != newForeground) {
-            return updateRulesForDataUsageRestrictionsUL(uid, notify);
+            updateRulesForDataUsageRestrictionsUL(uid);
         }
-        return null;
+    }
+
+    static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
+        return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
+    }
+
+    static boolean isProcStateAllowedWhileOnRestrictBackground(int procState) {
+        return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
     }
 
     void updateRulesForPowerSaveUL() {
@@ -2805,7 +2681,7 @@
                 // Skip if it had no restrictions to begin with
                 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
             }
-            updateRulesForPowerRestrictionsUL(uid, oldRules, paroled, true);
+            updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
         }
     }
 
@@ -2885,10 +2761,10 @@
                     final int uid = UserHandle.getUid(user.id, app.uid);
                     switch (type) {
                         case TYPE_RESTRICT_BACKGROUND:
-                            updateRulesForDataUsageRestrictionsUL(uid, true);
+                            updateRulesForDataUsageRestrictionsUL(uid);
                             break;
                         case TYPE_RESTRICT_POWER:
-                            updateRulesForPowerRestrictionsUL(uid, true);
+                            updateRulesForPowerRestrictionsUL(uid);
                             break;
                         default:
                             Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
@@ -2914,7 +2790,7 @@
                 updateRuleForDeviceIdleUL(uid);
                 updateRuleForRestrictPowerUL(uid);
                 // Update internal rules.
-                updateRulesForPowerRestrictionsUL(uid, true);
+                updateRulesForPowerRestrictionsUL(uid);
             }
         }
     }
@@ -2978,10 +2854,6 @@
         mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
         mPowerSaveWhitelistAppIds.delete(uid);
         mPowerSaveTempWhitelistAppIds.delete(uid);
-        synchronized (mDispatchedThirdLock) {
-            mLastHandledProcStateSeq.delete(uid);
-            mDispatchFlagsForCurProcStateSeq.delete(uid);
-        }
 
         // ...then update iptables asynchronously.
         mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
@@ -3007,10 +2879,10 @@
         updateRuleForRestrictPowerUL(uid);
 
         // Update internal state for power-related modes.
-        updateRulesForPowerRestrictionsUL(uid, true);
+        updateRulesForPowerRestrictionsUL(uid);
 
         // Update firewall and internal rules for Data Saver Mode.
-        updateRulesForDataUsageRestrictionsUL(uid, true);
+        updateRulesForDataUsageRestrictionsUL(uid);
     }
 
     /**
@@ -3051,16 +2923,11 @@
      *
      * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
      *
-     * @param uid The uid for which the rules have to be updated.
-     * @param notify Indicates whether to notify network policy listeners if the rules are updated.
-     *
-     * @return ReturnStatus includes new updated rules and whether network policy listeners
-     *         (INetworkPolicyListener) need to be notified.
      */
-    private ReturnStatus updateRulesForDataUsageRestrictionsUL(int uid, boolean notify) {
+    private void updateRulesForDataUsageRestrictionsUL(int uid) {
         if (!isUidValidForWhitelistRules(uid)) {
             if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
-            return new ReturnStatus(false, RULE_NONE);
+            return;
         }
 
         final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
@@ -3155,12 +3022,9 @@
                         + ", oldRule=" + uidRulesToString(oldUidRules));
             }
 
-            if (notify) {
-                mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
-            }
-            return new ReturnStatus(true, newUidRules);
+            // Dispatch changed rule to existing listeners.
+            mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
         }
-        return new ReturnStatus(false, newUidRules);
     }
 
     /**
@@ -3181,18 +3045,16 @@
      * <p>
      * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
      */
-    private ReturnStatus updateRulesForPowerRestrictionsUL(int uid, boolean notify) {
+    private void updateRulesForPowerRestrictionsUL(int uid) {
         final int oldUidRules = mUidRules.get(uid, RULE_NONE);
 
-        final ReturnStatus status = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false,
-                notify);
+        final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
 
-        if (status.mNewUidRules == RULE_NONE) {
+        if (newUidRules == RULE_NONE) {
             mUidRules.delete(uid);
         } else {
-            mUidRules.put(uid, status.mNewUidRules);
+            mUidRules.put(uid, newUidRules);
         }
-        return status;
     }
 
     /**
@@ -3201,17 +3063,13 @@
      * @param uid the uid of the app to update rules for
      * @param oldUidRules the current rules for the uid, in order to determine if there's a change
      * @param paroled whether to ignore idle state of apps and only look at other restrictions.
-     * @param notify whether to notify network policy listeners (INetworkPolicyListener) if the
-     *               rules are updated.
      *
-     * @return ReturnStatus includes new updated rules and whether network policy listeners
-     *         (INetworkPolicyListener) need to be notified.
+     * @return the new computed rules for the uid
      */
-    private ReturnStatus updateRulesForPowerRestrictionsUL(int uid, int oldUidRules,
-            boolean paroled, boolean notify) {
+    private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
         if (!isUidValidForBlacklistRules(uid)) {
             if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
-            return new ReturnStatus(false, RULE_NONE);
+            return RULE_NONE;
         }
 
         final boolean isIdle = !paroled && isUidIdle(uid);
@@ -3263,23 +3121,10 @@
                         + ", newRule=" + uidRulesToString(newUidRules)
                         + ", oldRule=" + uidRulesToString(oldUidRules));
             }
-            if (notify) {
-                mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
-            }
-            return new ReturnStatus(true, newUidRules);
+            mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
         }
 
-        return new ReturnStatus(false, newUidRules);
-    }
-
-    private static final class ReturnStatus {
-        boolean mNeedToNotify;
-        int mNewUidRules;
-
-        ReturnStatus(boolean needToNotify, int newUidRules) {
-            mNeedToNotify = needToNotify;
-            mNewUidRules = newUidRules;
-        }
+        return newUidRules;
     }
 
     private class AppIdleStateChangeListener
@@ -3293,7 +3138,7 @@
                 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
                 synchronized (mUidRulesFirstLock) {
                     updateRuleForAppIdleUL(uid);
-                    updateRulesForPowerRestrictionsUL(uid, true);
+                    updateRulesForPowerRestrictionsUL(uid);
                 }
             } catch (NameNotFoundException nnfe) {
             }
@@ -3353,26 +3198,13 @@
                 case MSG_RULES_CHANGED: {
                     final int uid = msg.arg1;
                     final int uidRules = msg.arg2;
-                    if (uidRules != RULE_INVALID) {
-                        dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
+                    dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
+                    final int length = mListeners.beginBroadcast();
+                    for (int i = 0; i < length; i++) {
+                        final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
+                        dispatchUidRulesChanged(listener, uid, uidRules);
                     }
-                    final Long procStateSeq = (Long) msg.obj;
-                    if (procStateSeq != null) {
-                        synchronized (mDispatchedThirdLock) {
-                            if (mLastHandledProcStateSeq.get(uid) == procStateSeq) {
-                                setDispatchedFlagDL(uid, procStateSeq, FLAG_UID_RULES_DISPATCHED);
-                                checkAndNotifyDL(uid, procStateSeq);
-                            }
-                        }
-                    }
-                    if (uidRules != RULE_INVALID) {
-                        final int length = mListeners.beginBroadcast();
-                        for (int i = 0; i < length; i++) {
-                            final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
-                            dispatchUidRulesChanged(listener, uid, uidRules);
-                        }
-                        mListeners.finishBroadcast();
-                    }
+                    mListeners.finishBroadcast();
                     return true;
                 }
                 case MSG_METERED_IFACES_CHANGED: {