如何以编程方式使用SSID,安全性和密码添加网络?

时间:2018-03-19 11:57:34

标签: android android-wifi wifimanager

我可以使用以下代码连接特定网络。但我想通过使用SSID,安全选项和密码来添加网络。

     public void connectToSelectedNetwork(WifiManager wifiManager, String networkSSID, String password, boolean open_secured) {
        try {
            WifiConfiguration wifiConfig = new WifiConfiguration();
            wifiConfig.SSID = "\"" + networkSSID + "\"";

            if (!open_secured)
                wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            else {
                wifiConfig.preSharedKey = "\"" + password + "\"";
                wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            }


//            WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
//            int netId = wifiManager.addNetwork(wifiConfig);
            int netID = wifiManager.addNetwork(wifiConfig);
            if (wifiConfig.SSID != null && wifiConfig.SSID.equals("\"" + networkSSID + "\"")) {
                wifiManager.disconnect();
                wifiManager.enableNetwork(netID, true);
                wifiManager.saveConfiguration();
                wifiManager.reconnect();
            }
//            Toast.makeText(SettingsActivity.this,"position "+position+" "+netID,Toast.LENGTH_LONG).show();
//            PreviousNetworkID.add(position,netID);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("logs " + e.toString());
        }
    }

更具体地说明这个问题。我在下面添加相关图片。enter image description here

0 个答案:

没有答案