程序化地连接到特定的wifi

问题描述 投票:0回答:1

我想在安卓系统中以编程方式连接到特定的wifi。我参考了很多链接。但仍然没有达到目标。我按照下面的代码来连接特定的wifi。

 WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
  WifiConfiguration configuration = new WifiConfiguration();
                                    configuration.SSID = String.format("\"%s\"", "ssid");
                                    configuration.preSharedKey = String.format("\"%s\"", "paasword");
                                    configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                                    int netId = wifiManager.addNetwork(configuration);
                                    wifiManager.disconnect();
                                    wifiManager.enableNetwork(netId,true);
                                    wifiManager.reconnect();

When I was try to run this code stuff... wifi connection will be disconnected and again automatically connected previous wifi network.I am using reddmi 6a mobile(version 9) for testing purpose.Can any one guide me how to resolve this one.

先谢谢你了。

android android-wifi
1个回答
3
投票

我相信你需要循环通过所有可用的网络,然后连接到正确的一个,如果它是可用的。

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

         break;
    }else{Log.e("TAG","Network Not Available")}           
}
© www.soinside.com 2019 - 2024. All rights reserved.