WifiNetworkSpecifier: get context reflectively

Temporarily use reflection to get the context
in order to allow framework-wifi to build
against @SystemApi stubs. Will remove reflective
call once refactor is complete to allow
WifiNetworkSpecifier to get the context using
formal APIs.

Bug: 144102365
Test: Ran CTS Verifier NetworkRequest tests, verified package name
in adb logs.
Change-Id: Ib507b449f81e9ce88cdb9190e9f8390eb25819b7
diff --git a/wifi/java/android/net/wifi/WifiNetworkSpecifier.java b/wifi/java/android/net/wifi/WifiNetworkSpecifier.java
index 07afd7f..444e1ef 100644
--- a/wifi/java/android/net/wifi/WifiNetworkSpecifier.java
+++ b/wifi/java/android/net/wifi/WifiNetworkSpecifier.java
@@ -20,7 +20,7 @@
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.app.ActivityThread;
+import android.app.Application;
 import android.net.MacAddress;
 import android.net.MatchAllNetworkSpecifier;
 import android.net.NetworkRequest;
@@ -30,8 +30,11 @@
 import android.os.PatternMatcher;
 import android.os.Process;
 import android.text.TextUtils;
+import android.util.Log;
 import android.util.Pair;
 
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
 import java.nio.charset.CharsetEncoder;
 import java.nio.charset.StandardCharsets;
 import java.util.Objects;
@@ -41,6 +44,7 @@
  * {@link WifiNetworkSpecifier.Builder} class to create an instance.
  */
 public final class WifiNetworkSpecifier extends NetworkSpecifier implements Parcelable {
+    private static final String TAG = "WifiNetworkSpecifier";
 
     /**
      * Builder used to create {@link WifiNetworkSpecifier} objects.
@@ -436,7 +440,22 @@
                     mBssidPatternMatcher,
                     buildWifiConfiguration(),
                     Process.myUid(),
-                    ActivityThread.currentApplication().getApplicationContext().getOpPackageName());
+                    getCurrentApplicationReflectively().getApplicationContext().getOpPackageName());
+        }
+
+        // TODO(b/144102365): Remove once refactor is complete
+        private static Application getCurrentApplicationReflectively() {
+            try {
+                // reflection for static method android.app.ActivityThread#currentApplication()
+                Class<?> klass = Class.forName("android.app.ActivityThread");
+                Method currentApplicationMethod = klass.getDeclaredMethod("currentApplication");
+                Object result = currentApplicationMethod.invoke(null);
+                return (Application) result;
+            } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException
+                    | InvocationTargetException e) {
+                Log.e(TAG, "Failed to call ActivityThread#currentApplication() reflectively!", e);
+                throw new RuntimeException(e);
+            }
         }
     }