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

时间:2018-08-16 05:54:22

标签: java android

我想通过android应用测试wifi连接,以检查输入的wifi ssid和密码是否正确。我如何检查给定的ssid和密码是否正确?

1 个答案:

答案 0 :(得分:1)

这是我们在应用程序中所做的:

  1. 我们确保已启用wifi
  2. 我们用ssid和pw创建一个WifiConfiguration(请注意,WifiConfiguration.SSID和WifiConfiguration.preSharedKey用引号引起来,因此,如果ssid是示例,而pw是密码,则WifiConfiguration.SSID = "\"example\""WifiConfiguration.preSharedKey = "\"password\""
  3. 我们将WifiConfiguration添加到WifiManager(WifiManager.addNetwork(WifiConfiguration)
  4. 我们检查返回值(它是一个networkId)是否为-1,表示操作不成功
  5. 我们告诉WifiManager从上一步启用networkId并尝试连接(WifiManager.enableNetwork(netId, true)
  6. 我们检查与此WifiConfiguration的协商是否成功。此步骤包含一些丑陋的代码,我很想得到其他一些想法,但是它可以起作用:

    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;
    }