How to detect WiFi tethering state

Using reflection:

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();
  }
}

As you can see here


First, you need to get WifiManager:

Context context = ...
final WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

Then:

public static boolean isSharingWiFi(final WifiManager manager)
{
    try
    {
        final Method method = manager.getClass().getDeclaredMethod("isWifiApEnabled");
        method.setAccessible(true); //in the case of visibility change in future APIs
        return (Boolean) method.invoke(manager);
    }
    catch (final Throwable ignored)
    {
    }

    return false;
}

Also you need to request a permission in AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

In addition to the reflexion, to get the Wifi tethering status update, you can listen to this broadcast Action :

IntentFilter filter = new IntentFilter("android.net.wifi.WIFI_AP_STATE_CHANGED");

To get all tethering option update :

IntentFilter filter = new IntentFilter("android.net.conn.TETHER_STATE_CHANGED");

Those actions are hidden inside the Android source code

Tags:

Android