gpt4 book ai didi

java - 以编程方式断开连接后重新连接到 WiFi 网络

转载 作者:行者123 更新时间:2023-12-01 10:02:12 24 4
gpt4 key购买 nike

我通过编程方式与 WiFi 网络断开了

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.disconnect();
DisconnectWifi discon = new DisconnectWifi();
registerReceiver(discon, new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));


public class DisconnectWifi extends BroadcastReceiver {

@Override
public void onReceive(Context c, Intent intent) {
WifiManager wifi = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
if(!intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE).toString().equals(SupplicantState.SCANNING))
wifi.disconnect();
}
}

但我无法再次重新连接到同一网络。我尝试使用以下命令重新连接:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.reconnect();

但无法连接。我现在如何重新连接到 WiFi 网络?

谢谢

最佳答案

所以完整的、简化的解决方案看起来像这样:

WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
wifiConfig.preSharedKey = String.format("\"%s\"", key);

WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
//remember id
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();

希望对你有帮助!!

关于java - 以编程方式断开连接后重新连接到 WiFi 网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36711586/

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