java - 以编程方式连接到 wifi 网络(首先访问 ssid)?

标签 java android android-studio networking wifimanager

我想连接第一次 wifi 网络(以前没有保存过)。如果我之前连接到 wifi,下面的代码运行良好并且我访问 wifi,但是如果我第一次尝试连接,没有任何反应。为什么会这样?

String networkSSID = "myssid";
String networkPass = "mypass";
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\"";
conf.preSharedKey = "\""+ networkPass +"\"";

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

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

        break;
    }
}

最佳答案

有点晚了,但它可能对其他人有帮助。 你有点,做错了。 您正在添加一个网络(之前未配置的网络),然后您尝试连接到已配置的网络(另一个不同的网络),两者都具有相同的 SSID。 相反,试试这个:

netId = wifiManager.addNetwork(conf);
if (netId == -1) {
    netId = //your procedure of getting the netId from wifiManager.getConfiguredNetworks()
}
wifiManager.enableNetwork(netId, true);

在 Kotlin 中,它看起来像这样:

var netId = wifiManager.addNetwork(conf)
if (netId == -1) netId = getExistingNetworkId(ssid)
if (!wifiManager.enableNetwork(netId, true)) {
//Handle failure
}

...
private fun getExistingNetworkId(ssid: String): Int {
    wifiManager.configuredNetworks?.let {
        return it.firstOrNull { it.SSID.trim('"') == ssid.trim('"') }?.networkId ?: -1
    }
    //Unable to find proper NetworkId to connect to
    return -1
}

这应该足够了。您不需要断开/重新连接部分。

关于java - 以编程方式连接到 wifi 网络(首先访问 ssid)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42252685/

相关文章:

java - 执行失败异常

java - spring security HTTP状态403-访问被拒绝

java - 媒体类型 "multipart/form-data"没有可用的 MessageBodyWriter

java - Android 查找 SDCard 上的文件

android - 使用 Android Studio 调试时源文件错误

android - Android Studio 中的 lint 如何与 IntelliJ 检查集成?

java - "final remark"中CMS的具体工作是什么?

java - 从文件中获取唯一的条目

android - flutter -FCM : how to store background message to SQLite

android - 为什么 ImmutableList 会导致 Jetpack Compose 中的重组?