Android: Programmatically Turn on WiFi hotspot

夙愿已清 提交于 2019-11-29 07:19:01

I had the same issue. You must to erase the following code line:

netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);    

That works for me in versions 4.1.1, 4.2 and 4.3.

Try this code .I test in android 5.0.1 :

      public boolean setHotSpot(String SSID,String passWord){
        Method[] mMethods = mWifiManager.getClass().getDeclaredMethods();

        for(Method mMethod: mMethods){

            if(mMethod.getName().equals("setWifiApEnabled")) {
                WifiConfiguration netConfig = new WifiConfiguration();
                if(passWord==""){
                    netConfig.SSID = SSID;
                    netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                    netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                    netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                    netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);     
                }else{
                netConfig.SSID = SSID ;
                netConfig.preSharedKey = passWord;
                netConfig.hiddenSSID = true;
                netConfig.status = WifiConfiguration.Status.ENABLED;
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                }
                try {              
                    mMethod.invoke(mWifiManager, netConfig,false);
                    mWifiManager.saveConfiguration();
                    return true;

                } catch (Exception e) {
                  e.getMessage();
                }
            }
        }
        return false; 
  }

Insert this permission in AndroidManifest:

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

If you are using WPA_PSK authentication, you have to specify preSharedKey.

        netConfig.preSharedKey = "testPassword";
        netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

Otherwise it will crash and restart the device.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!