首页 > 解决方案 > 如何以编程方式连接到 Android 中的 WPA2-PSK Wi-Fi 网络?

问题描述

我需要以编程方式连接到 Android 中的 WiFi(esp8266 nodeMCU)。此网络的 SSID 为 Hide,其安全性为 WPA2-PSK。它也没有连接到互联网,它是一个本地网络。

我尝试使用此代码,但无法连接到 HotSpot。 “enableNetworkBoolean”为“假”。但我可以在设置中连接到热点。

public class ConnWifi  {

public void Connect(Context context){
    WifiConfiguration config = new WifiConfiguration();
    config.SSID = ""reyhan112233"";
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        config.SSID = "reyhan112233";
    }
    config.preSharedKey = ""reyhan112233"";
    config.hiddenSSID = true;
    config.status = WifiConfiguration.Status.ENABLED;
    config.allowedGroupCiphers.set(WifiConfiguration.G  roupCipher.TKIP);
    config.allowedGroupCiphers.set(WifiConfiguration.G  roupCipher.CCMP);
    config.allowedKeyManagement.set(WifiConfiguration.  KeyMgmt.WPA_PSK);
    config.allowedPairwiseCiphers.set(WifiConfiguratio  n.PairwiseCipher.TKIP);
    config.allowedPairwiseCiphers.set(WifiConfiguratio  n.PairwiseCipher.CCMP);
    config.allowedProtocols.set(WifiConfiguration.Prot  ocol.RSN);
    config.allowedProtocols.set(WifiConfiguration.Prot  ocol.WPA);

    WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI  _SERVICE);

    int networkId = wifiManager.addNetwork(config);
    if(networkId != -1){
        connectWifi(config, wifiManager);
    }
}

private void connectWifi(WifiConfiguration config , WifiManager wifiManager) {
    wifiManager.disconnect();
    wifiManager.setWifiEnabled(true);
    boolean enableNetworkBoolean = wifiManager.enableNetwork(config.networkId, true);

    boolean reconnectBoolean = wifiManager.reconnect();
    boolean changeHappen = wifiManager.saveConfiguration();
    if(enableNetworkBoolean && reconnectBoolean && changeHappen){
    }
    else{

    }
}

标签: androidwifi

解决方案


推荐阅读