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.

1 Answer 1

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" />
Sign up to request clarification or add additional context in comments.

6 Comments

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 Do I need a rooted phone? i don't think so, as my device is not rooted and it's working.
@CalumMcCall may be you should try printStackTrace in setWifiApState method to see error.
Turned out I was missing the "CHANGE_NETWORK_STATE" permission. Thanks for your help!
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.