如何在Android上连接到特定的WiFi SSID?

时间:2018-06-04 02:08:17

标签: android connection wifi

我想使用this code通过SSID连接到特定的wifi。

它没有在String中连接到wifi的SSID。我是Android的新手,如果有人告诉我这个问题会很好。 (当然,不修复代码)!

public class DiscoverActTest extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String networkSSID = "DIRECT";
        String networkPass = "123456789";

        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\"";
        conf.wepKeys[0] = "\"" + networkPass + "\"";
        conf.wepTxKeyIndex = 0;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        conf.preSharedKey = "\""+ networkPass +"\"";
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

        WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(WIFI_SERVICE);
        wifiManager.addNetwork(conf);

         wifiManager.setWifiEnabled(true);
        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        for( WifiConfiguration i : list ) {
            if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
                wifiManager.disconnect();
                wifiManager.enableNetwork(i.networkId, true);
                wifiManager.reconnect();
                break;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

更改

conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

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