gpt4 book ai didi

java - 如果已经连接到另一个 WiFi,则连接到特定 WiFi

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

这两天我一直在苦苦挣扎,我找不到解决办法。我尝试了这段代码,但随着时间的推移,它在 Android 5(Lollipop) 上运行,但在 7.1.1.(Nougat) 上不起作用。我有另一个场景,手机失去连接,之后,它需要返回到旧 Wifi。

public void setWifiConnection1(View view){
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);


WifiConfiguration wc = new WifiConfiguration();
WifiInfo wifiInfo = wifiManager.getConnectionInfo();

wc.SSID = "\"NETWORK_NAME\"";
wc.preSharedKey = "\"PASSWORD\"";
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.priority = 999999;
wifiManager.setWifiEnabled(true);
int netId = wifiManager.addNetwork(wc);
if (netId == -1) {
netId = getExistingNetworkId(wc.SSID);
}
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
}

private int getExistingNetworkId(String SSID) {

WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
if (configuredNetworks != null) {
for (WifiConfiguration existingConfig : configuredNetworks) {
if (existingConfig.SSID.equals(SSID)) {
return existingConfig.networkId;
}
}
}
return -1;
}

最佳答案

wifiManager.setWifiEnabled(true);

您不能在该行之后立即执行您的代码。您应该执行 wifiManager.isWifiEnabled() 检查并订阅广播(如果它被禁用)。

下一步...

wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();

这部分很奇怪:你为什么断开连接?请注意,大多数 WifiManager 操作都是异步的,因此您每次都会观察到不同的结果 - 真正的“断开连接”可能会在您尝试启用所需网络后发生。

你总能从系统API中获得灵感:https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r30/wifi/java/android/net/wifi/WifiManager.java#2773

所以正确的顺序是:

wifiManager.addNetwork(...);
wifiManager.enableNetwork(netId, true);
wifiManager.saveConfiguration();
wifiManager.reconnect();

但如果允许的话,直接使用系统API会更方便。

关于java - 如果已经连接到另一个 WiFi,则连接到特定 WiFi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47593170/

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