Search code examples
javaandroidandroid-wifi

Turning on wifi tethering programmatically


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.


Solution

  • 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" />