简体   繁体   English

如何使用给定的 ssid 和密码测试 wifi 连接并返回给定 ssid 和密码是否正确的结果

[英]How to test wifi connection using given ssid and password and returns result of whether given ssid and password is correct or not

I want to test wifi connection through android app to check whether entered wifi ssid and password is correct or not.我想通过android应用程序测试wifi连接以检查输入的wifi ssid和密码是否正确。 How i can check whether the given ssid and password is correct?如何检查给定的 ssid 和密码是否正确?

Here's what we do in our app:这是我们在我们的应用程序中所做的:

  1. We ensure that the wifi is enabled我们确保 wifi 已启用
  2. We create a WifiConfiguration with the ssid and pw (note that WifiConfiguration.SSID and WifiConfiguration.preSharedKey are surrounded in quotes so that if the ssid is example and the pw is password then WifiConfiguration.SSID = "\\"example\\"" and WifiConfiguration.preSharedKey = "\\"password\\""我们使用 ssid 和 pw 创建一个 WifiConfiguration(注意 WifiConfiguration.SSID 和 WifiConfiguration.preSharedKey 用引号括起来,这样如果 ssid 是 example 并且 pw 是密码,那么WifiConfiguration.SSID = "\\"example\\""WifiConfiguration.preSharedKey = "\\"password\\""
  3. We add the WifiConfiguration to the WifiManager ( WifiManager.addNetwork(WifiConfiguration) )我们将 WifiConfiguration 添加到 WifiManager ( WifiManager.addNetwork(WifiConfiguration) )
  4. We check the return value (which is a networkId) if it is -1 then the operation was not successful我们检查返回值(它是一个 networkId),如果它是 -1 则操作不成功
  5. We tell the WifiManager fo enable the networkId from the previous step and attempt to connect ( WifiManager.enableNetwork(netId, true) )我们告诉 WifiManager 启用上一步中的 networkId 并尝试连接( WifiManager.enableNetwork(netId, true)
  6. We check if the negotiation with this WifiConfiguration was successful.我们检查与此 WifiConfiguration 的协商是否成功。 This step has some ugly code, and I would love to get some other ideas, but it works:这一步有一些丑陋的代码,我很想得到一些其他的想法,但它有效:

     private static boolean checkWifiNegotiation(WifiManager wifiManager, int netId) { boolean startedHandshake = false; boolean successful = false; for (int i = 0; i < 30; i++) { try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } SupplicantState currentState = wifiManager.getConnectionInfo().getSupplicantState(); if (!startedHandshake && currentState.equals(SupplicantState.FOUR_WAY_HANDSHAKE)) { startedHandshake = true; } else if (startedHandshake) { if (currentState.equals(SupplicantState.DISCONNECTED)) { break; } else if (currentState.equals(SupplicantState.COMPLETED)) { successful = true; break; } } wifiManager.enableNetwork(netId, true); } // no matter what happened above, if COMPLETED then we have the correct pw if (!successful && wifiManager.getConnectionInfo().getSupplicantState().equals(SupplicantState.COMPLETED)) { successful = true; } return successful; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM