首页 > 解决方案 > 如何在 Android 上连接到特定的 wifi SSID?

问题描述

我想使用此代码通过 SSID 连接到特定的 wifi 。

它没有连接到字符串中的 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;
            }
        }
    }
}

标签: androidconnectionwifi

解决方案


改变

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

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

推荐阅读