gpt4 book ai didi

java - 使用 WifiManager 连接到无线网络 (wpa2)

转载 作者:行者123 更新时间:2023-11-30 00:14:49 25 4
gpt4 key购买 nike

尝试创建一个 NFC 标签应用,将 Wifi 凭据存储在 NFC 标签上,然后将其读出。从那里我获取字符串并使用它并通过 wifimanager 放置凭据以连接到无线网络。我很确定我的代码是正确的,但它仍然没有连接。我错过了什么吗?我尝试连接的 channel 是 WPA2。

我如何为函数提取数据:

@Override
public void onClick(View v)
{
String payload = _textViewData.getText().toString();
String[] parts = payload.split("-");
String SSID = parts[0];
String Password = parts[1];

part1.setText(SSID);
part2.setText(Password);
connectToWifi(SSID, Password);

}
});

更新:连接函数

 private void connectToWifi(final String networkSSID, final String networkPassword){
if (!wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(true);
}
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = String.format("\"%s\"", networkSSID);
conf.preSharedKey = "\""+ networkPassword +"\"";

WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);

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

break;
}
}
}

更新 2:

我将我的网络切换到 WPA 并且它有效,但似乎不适用于 WPA2,这可能吗?

最佳答案

要连接 WPA 网络,您需要像这样添加密码:

conf.preSharedKey = "\""+ networkPass +"\"";

对于开放网络,您需要这样做:

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

然后,您需要将其添加到 Android wifi 管理器设置中:

WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); 
wifiManager.addNetwork(conf);

之后你必须启用它。

List<WifiConfiguration> wifiList = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : wifiList ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.status = WifiConfiguration.Status.ENABLED;
wifiManager.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifiManager.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifiManager.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifiManager.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wifiManager.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wifiManager.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wifiManager.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifiManager.reconnect();

break;
}
}

编码愉快!!

关于java - 使用 WifiManager 连接到无线网络 (wpa2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47466211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com