Improve NetworkPolicyManagerTest

Basically, this commit is to fix the comments left on
aosp/1737395.
- Remove MeterednessConfigurationRule since this test won't
  change meteredness.
- Launch activity without checking network access because such
  behavior has covered by DataSaverModeTest. This test can only
  focus on the network rule changed when the app is in the
  foreground or background.

Also improve test by
- Having a new function to just launch the activity without
  checking network status.
- Having a callback design when launching an activity to ensure
  that the ACTION_FINISH_ACTIVITY is registered before leaving
  launchActivity() method. Without this design, there might be a
  race when activity is launched but ACTION_FINISH_ACTIVITY
  has not registered before test calls finishActivity().
  When the issue is happened, there is no way to fix it, so have
  a callback design to prevent this problem.

Ignore-AOSP-First: There is a merge conflict in AOSP.
Bug: 176289731
Test: atest CtsHostsideNetworkTests:HostsideNetworkPolicyManagerTests \
      #testIsUidNetworkingBlocked_withDataSaverMode \
      CtsHostsideNetworkTests:HostsideNetworkPolicyManagerTests \
      #testIsUidRestrictedOnMeteredNetworks --rerun-until-failure 100
Change-Id: I045e4a7dd0cec15f20e529024cd1fc06bcccd68f
diff --git a/tests/cts/hostside/app/src/com/android/cts/net/hostside/AbstractRestrictBackgroundNetworkTestCase.java b/tests/cts/hostside/app/src/com/android/cts/net/hostside/AbstractRestrictBackgroundNetworkTestCase.java
index 5b88f1b..79f1d45 100644
--- a/tests/cts/hostside/app/src/com/android/cts/net/hostside/AbstractRestrictBackgroundNetworkTestCase.java
+++ b/tests/cts/hostside/app/src/com/android/cts/net/hostside/AbstractRestrictBackgroundNetworkTestCase.java
@@ -53,6 +53,7 @@
 import android.os.BatteryManager;
 import android.os.Binder;
 import android.os.Bundle;
+import android.os.RemoteCallback;
 import android.os.SystemClock;
 import android.provider.DeviceConfig;
 import android.service.notification.NotificationListenerService;
@@ -137,6 +138,7 @@
 
     private static final int ACTIVITY_NETWORK_STATE_TIMEOUT_MS = 6_000;
     private static final int JOB_NETWORK_STATE_TIMEOUT_MS = 10_000;
+    private static final int LAUNCH_ACTIVITY_TIMEOUT_MS = 10_000;
 
     // Must be higher than NETWORK_TIMEOUT_MS
     private static final int ORDERED_BROADCAST_TIMEOUT_MS = NETWORK_TIMEOUT_MS * 4;
@@ -787,6 +789,22 @@
         mDeviceIdleDeviceConfigStateHelper.restoreOriginalValues();
     }
 
+    protected void launchActivity() throws Exception {
+        turnScreenOn();
+        final CountDownLatch latch = new CountDownLatch(1);
+        final Intent launchIntent = getIntentForComponent(TYPE_COMPONENT_ACTIVTIY);
+        final RemoteCallback callback = new RemoteCallback(result -> latch.countDown());
+        launchIntent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
+        mContext.startActivity(launchIntent);
+        // There might be a race when app2 is launched but ACTION_FINISH_ACTIVITY has not registered
+        // before test calls finishActivity(). When the issue is happened, there is no way to fix
+        // it, so have a callback design to make sure that the app is launched completely and
+        // ACTION_FINISH_ACTIVITY will be registered before leaving this method.
+        if (!latch.await(LAUNCH_ACTIVITY_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
+            fail("Timed out waiting for launching activity");
+        }
+    }
+
     protected void launchComponentAndAssertNetworkAccess(int type) throws Exception {
         launchComponentAndAssertNetworkAccess(type, true);
     }
diff --git a/tests/cts/hostside/app/src/com/android/cts/net/hostside/NetworkPolicyManagerTest.java b/tests/cts/hostside/app/src/com/android/cts/net/hostside/NetworkPolicyManagerTest.java
index ad7ec9e..a0d88c9 100644
--- a/tests/cts/hostside/app/src/com/android/cts/net/hostside/NetworkPolicyManagerTest.java
+++ b/tests/cts/hostside/app/src/com/android/cts/net/hostside/NetworkPolicyManagerTest.java
@@ -18,37 +18,28 @@
 
 import static android.os.Process.SYSTEM_UID;
 
+import static com.android.cts.net.hostside.NetworkPolicyTestUtils.assertIsUidRestrictedOnMeteredNetworks;
 import static com.android.cts.net.hostside.NetworkPolicyTestUtils.assertNetworkingBlockedStatusForUid;
-import static com.android.cts.net.hostside.NetworkPolicyTestUtils.canChangeActiveNetworkMeteredness;
 import static com.android.cts.net.hostside.NetworkPolicyTestUtils.isUidNetworkingBlocked;
-import static com.android.cts.net.hostside.NetworkPolicyTestUtils.isUidRestrictedOnMeteredNetworks;
 import static com.android.cts.net.hostside.NetworkPolicyTestUtils.setRestrictBackground;
 import static com.android.cts.net.hostside.Property.BATTERY_SAVER_MODE;
 import static com.android.cts.net.hostside.Property.DATA_SAVER_MODE;
 
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeTrue;
 
 import org.junit.After;
 import org.junit.Before;
-import org.junit.Rule;
 import org.junit.Test;
 
 public class NetworkPolicyManagerTest extends AbstractRestrictBackgroundNetworkTestCase {
     private static final boolean METERED = true;
     private static final boolean NON_METERED = false;
 
-    @Rule
-    public final MeterednessConfigurationRule mMeterednessConfiguration =
-            new MeterednessConfigurationRule();
-
     @Before
     public void setUp() throws Exception {
         super.setUp();
 
-        assumeTrue(canChangeActiveNetworkMeteredness());
-
         registerBroadcastReceiver();
 
         removeRestrictBackgroundWhitelist(mUid);
@@ -145,13 +136,14 @@
             removeRestrictBackgroundWhitelist(mUid);
 
             // Make TEST_APP2_PKG go to foreground and mUid will be allowed temporarily.
-            launchComponentAndAssertNetworkAccess(TYPE_COMPONENT_ACTIVTIY);
+            launchActivity();
             assertForegroundState();
             assertNetworkingBlockedStatusForUid(mUid, METERED,
                     false /* expectedResult */); // Match NTWK_ALLOWED_TMP_ALLOWLIST
 
             // Back to background.
             finishActivity();
+            assertBackgroundState();
             assertNetworkingBlockedStatusForUid(mUid, METERED,
                     true /* expectedResult */); // Match NTWK_BLOCKED_BG_RESTRICT
         } finally {
@@ -222,26 +214,27 @@
             // enabled and mUid is not in the restrict background whitelist and TEST_APP2_PKG is not
             // in the foreground. For other cases, it will return false.
             setRestrictBackground(true);
-            assertTrue(isUidRestrictedOnMeteredNetworks(mUid));
+            assertIsUidRestrictedOnMeteredNetworks(mUid, true /* expectedResult */);
 
             // Make TEST_APP2_PKG go to foreground and isUidRestrictedOnMeteredNetworks() will
             // return false.
-            launchComponentAndAssertNetworkAccess(TYPE_COMPONENT_ACTIVTIY);
+            launchActivity();
             assertForegroundState();
-            assertFalse(isUidRestrictedOnMeteredNetworks(mUid));
+            assertIsUidRestrictedOnMeteredNetworks(mUid, false /* expectedResult */);
             // Back to background.
             finishActivity();
+            assertBackgroundState();
 
             // Add mUid into restrict background whitelist and isUidRestrictedOnMeteredNetworks()
             // will return false.
             addRestrictBackgroundWhitelist(mUid);
-            assertFalse(isUidRestrictedOnMeteredNetworks(mUid));
+            assertIsUidRestrictedOnMeteredNetworks(mUid, false /* expectedResult */);
             removeRestrictBackgroundWhitelist(mUid);
         } finally {
             // Restrict background is disabled and isUidRestrictedOnMeteredNetworks() will return
             // false.
             setRestrictBackground(false);
-            assertFalse(isUidRestrictedOnMeteredNetworks(mUid));
+            assertIsUidRestrictedOnMeteredNetworks(mUid, false /* expectedResult */);
         }
     }
 }
diff --git a/tests/cts/hostside/app/src/com/android/cts/net/hostside/NetworkPolicyTestUtils.java b/tests/cts/hostside/app/src/com/android/cts/net/hostside/NetworkPolicyTestUtils.java
index 4f9ce7c..58667b1 100644
--- a/tests/cts/hostside/app/src/com/android/cts/net/hostside/NetworkPolicyTestUtils.java
+++ b/tests/cts/hostside/app/src/com/android/cts/net/hostside/NetworkPolicyTestUtils.java
@@ -435,6 +435,11 @@
         PollingCheck.waitFor(() -> (expectedResult == isUidNetworkingBlocked(uid, metered)));
     }
 
+    public static void assertIsUidRestrictedOnMeteredNetworks(int uid, boolean expectedResult)
+            throws Exception {
+        PollingCheck.waitFor(() -> (expectedResult == isUidRestrictedOnMeteredNetworks(uid)));
+    }
+
     public static boolean isUidNetworkingBlocked(int uid, boolean meteredNetwork) {
         final UiAutomation uiAutomation = getInstrumentation().getUiAutomation();
         try {
diff --git a/tests/cts/hostside/app2/src/com/android/cts/net/hostside/app2/MyActivity.java b/tests/cts/hostside/app2/src/com/android/cts/net/hostside/app2/MyActivity.java
index 9fdb9c9..54eb927 100644
--- a/tests/cts/hostside/app2/src/com/android/cts/net/hostside/app2/MyActivity.java
+++ b/tests/cts/hostside/app2/src/com/android/cts/net/hostside/app2/MyActivity.java
@@ -17,7 +17,6 @@
 
 import static com.android.cts.net.hostside.app2.Common.ACTION_FINISH_ACTIVITY;
 import static com.android.cts.net.hostside.app2.Common.TAG;
-import static com.android.cts.net.hostside.app2.Common.TEST_PKG;
 import static com.android.cts.net.hostside.app2.Common.TYPE_COMPONENT_ACTIVTY;
 
 import android.app.Activity;
@@ -25,13 +24,10 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
-import android.os.AsyncTask;
 import android.os.Bundle;
-import android.os.RemoteException;
+import android.os.RemoteCallback;
 import android.util.Log;
 
-import com.android.cts.net.hostside.INetworkStateObserver;
-
 /**
  * Activity used to bring process to foreground.
  */
@@ -52,6 +48,11 @@
             }
         };
         registerReceiver(finishCommandReceiver, new IntentFilter(ACTION_FINISH_ACTIVITY));
+        final RemoteCallback callback = getIntent().getParcelableExtra(
+                Intent.EXTRA_REMOTE_CALLBACK);
+        if (callback != null) {
+            callback.sendResult(null);
+        }
     }
 
     @Override