如何检测WiFi网络共享状态

Nol*_*esh 6 android

我想知道如何检测WiFi网络共享的状态.我看过一篇文章:Android 2.3 wifi热点API但它不起作用!它总是返回WIFI_AP_STATE_DISABLED = 1.它不依赖于WiFi网络共享的真实状态.

Jac*_*rky 16

使用反射:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Method[] wmMethods = wifi.getClass().getDeclaredMethods();
for (Method method: wmMethods) {
  if (method.getName().equals("isWifiApEnabled")) {

    try {
      boolean isWifiAPenabled = method.invoke(wifi);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
  }
}
Run Code Online (Sandbox Code Playgroud)

正如你在这里看到的那样

  • 一个比另一个更好的答案,因为它只返回一个布尔值. (2认同)

Tob*_*iug 6

除了反射之外,要获取 Wifi 网络共享状态更新,您还可以收听此广播 Action :

IntentFilter filter = new IntentFilter("android.net.wifi.WIFI_AP_STATE_CHANGED");
Run Code Online (Sandbox Code Playgroud)

要获取所有网络共享选项更新:

IntentFilter filter = new IntentFilter("android.net.conn.TETHER_STATE_CHANGED");
Run Code Online (Sandbox Code Playgroud)

这些操作隐藏在 Android 源代码中