How to turn on/off wifi hotspot programmatically in Android 8.0 (Oreo)

Chandrakanth picture Chandrakanth · Aug 31, 2017 · Viewed 23.3k times · Source

I know how to turn on/off wifi hot spot using reflection in android using below method.

private static boolean changeWifiHotspotState(Context context,boolean enable) {
        try {
            WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            Method method = manager.getClass().getDeclaredMethod("setWifiApEnabled", WifiConfiguration.class,
                    Boolean.TYPE);
            method.setAccessible(true);
            WifiConfiguration configuration = enable ? getWifiApConfiguration(manager) : null;
            boolean isSuccess = (Boolean) method.invoke(manager, configuration, enable);
            return isSuccess;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

But the above method is not working Android 8.0(Oreo).

When I execute above method in Android 8.0, I am getting below statement in logcat.

com.gck.dummy W/WifiManager: com.gck.dummy attempted call to setWifiApEnabled: enabled = true

Is there any other way to on/off hotspot on android 8.0

Answer

Jon picture Jon · Mar 19, 2018

I thought the LocalOnlyHotspot route was the way to, but as @edsappfactory.com said in the comments - it only gives closed network, no internet access.

In Oreo hot-spotting/tethering moved to ConnectionManager, and its annotated @SystemApi, so (nominally) inaccessible.

As part of something else I was doing, I made an app and put it on github here. It uses reflection to get at the function and DexMaker to generate a subclass of ConnectionManager.OnStartTetheringCallback (which is also inaccessible).

Think it all works okay - bit rough around the edges, so please feel free to make better!

Relevant bits of code are in:

I lost patience trying to get my DexMaker-generated callback to fire the MyOnStartTetheringCallback so all that code is in disarray and commented out.