android - 如何以编程方式连接到 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{
}
}
解决方案
推荐阅读
- tortoisesvn - OneDrive 文件夹中的 TortoiseSVN 覆盖
- node.js - 将具有旧日期的数据流式传输到 bigquery 分区表中
- r - 使用 rsample 从评估拆分中删除观察结果
- c# - 迁移到 .Net Core v3.1 后 IAsyncQueryProvider 生成错误
- php - 从 php(变量)运行 bash 交互式脚本(带输入)
- java - 为什么实例只能被主要方法看到
- python - 删除pandas df中每一行的字符串中的最后一个字符
- html - 在引导行中对齐 mat-spinner
- sdk - 交互式多点触控应用的框架推荐
- python-3.x - 如何使用 conda-build“使用 CLI 选项进行构建”?