8

Is it possible to turn on the wifi hotspot programmatically, to enable tethering? I've tried the code here and here. Both examples execute without exception, but when I look in the "Tethering & portable hotspot" section in the wifi settings, the tethering is still disabled. Is this only possible for internal Google apps?

EDIT: I'm using Android 5.1 and I'm trying to do this without having to root the phone.

Community
  • 1
  • 1
CalumMcCall
  • 1,665
  • 4
  • 24
  • 46

1 Answers1

7

Try below code, to turning on wifi tethering programmatically. I have tested and it's working in my application.

public class WifiAccessManager {

    private static final String SSID = "1234567890abcdef";
    public static boolean setWifiApState(Context context, boolean enabled) {
        //config = Preconditions.checkNotNull(config);
        try {
            WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            if (enabled) {
                mWifiManager.setWifiEnabled(false);
            }
            WifiConfiguration conf = getWifiApConfiguration();
            mWifiManager.addNetwork(conf);

            return (Boolean) mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class).invoke(mWifiManager, conf, enabled);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static WifiConfiguration getWifiApConfiguration() {
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID =  SSID;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        return conf;
    }
}

Usage:

WifiAccessManager.setWifiApState(context, true);

Permission Require:

<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
Dhaval Patel
  • 10,119
  • 5
  • 43
  • 46
  • Thanks for the quick response! This does manage to turn off wifi, but setWifiApState returns false, and the tethering doesn't get activated. Do I need a rooted phone? I'm trying to do this without rooting the phone. – CalumMcCall Nov 17 '15 at 16:39
  • @CalumMcCall Do I need a rooted phone? i don't think so, as my device is not rooted and it's working. – Dhaval Patel Nov 17 '15 at 16:40
  • 1
    @CalumMcCall may be you should try printStackTrace in setWifiApState method to see error. – Dhaval Patel Nov 17 '15 at 16:41
  • Turned out I was missing the "CHANGE_NETWORK_STATE" permission. Thanks for your help! – CalumMcCall Nov 17 '15 at 16:49
  • 2
    This worked great until marshmallow. Now it doesn't work anymore. Any idea how to make it work in android 6 and above? Probably some new permission thing. They changed all that, but I don't know where to look. – stu Oct 26 '16 at 14:14
  • From what I can tell they broke it in marshmallow. Anybody know how to make it work anymore? – stu Dec 17 '17 at 18:18