Android 以编程方式测试 wifi 连接

Android test wifi connection programmatically

我正在为 IoT 设备编写 Android 应用程序。我必须为设备提供 WiFi 用户名和密码,因此我使用 android 应用程序来执行此操作。我有以下代码,但它似乎总是连接到网络天气或没有给出正确的密码。

这是我在 phone 连接的同一个 AP 上测试的。

所需的操作是

Disconnect from current AP -> Attempt to connect using credentials given -> Reconnect to original network.

我需要采取哪些步骤才能正确验证 wifi 网络和密码?

代码:

WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = "\"" + ssid + "\"";
    for(ScanResult sr: wifiList){
        if(sr.SSID.equals(ssid)){
            if(sr.capabilities.contains("WEP")){
                if(isNumeric(pass)){
                    conf.wepKeys[0] =  pass ;
                }else{
                    conf.wepKeys[0] = "\"" + pass + "\"";
                }
                conf.wepTxKeyIndex = 0;
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            }else if(sr.capabilities.contains("PSK")){
                conf.preSharedKey = "\""+ pass +"\"";
            }else if(sr.capabilities.contains("EAP")){
                wifiName.setError("EAP networks not supported");
                //todo support EAP
            }else{
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            }

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

            List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
            for( WifiConfiguration i : list ) {
                if(i.equals(conf)) {
                    wifiManager.disconnect();
                    if(!wifiManager.enableNetwork(i.networkId, true)){
                        wifiPassword.setError("Incorrect Password");
                        wifiManager.reconnect();
                        return;
                    }else{
                        wifiManager.reconnect();
                        addUser(deviceSN, ssid, pass);
                    }
                }
            }

            break;
        }
    }

您可能不需要扫描可用的 wifi 网络,您可以轻松地这样做:关注

public static void connectToWifi(Activity activity, String ssid, String password) {
        WifiConfiguration wifiConfig = new WifiConfiguration();

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

        WifiManager wifiManager = (WifiManager) activity.getSystemService(WIFI_SERVICE);
        wifiManager.setWifiEnabled(true);
        int netId = wifiManager.addNetwork(wifiConfig);
        wifiManager.disconnect();
        wifiManager.enableNetwork(netId, true);
        wifiManager.reconnect();
    }

您应该注册到 NETWORK_STATE_CHANGED_ACTION。

使用这个可以获取WI-FI网络状态,需要检查是否达到连接状态。如果设备在超时后仍未连接,则可以认为连接失败。

另一个有用的接收者可能是 SUPPLICANT_STATE_CHANGED_ACTION。

public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {

            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

            switch (info.getState()) {
                case CONNECTING:
                    break;
                case CONNECTED:
                    break;
                case DISCONNECTING:
                    break;
                case DISCONNECTED:
                    break;
                case SUSPENDED:
                    break;
                }
            }

看看是不是这样

public static boolean isConnectingToInternet(Context context){
  try {
      ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null) {
          NetworkInfo info[] = connectivity.getAllNetworkInfo();
          if (info != null) {
              for (int i = 0; i < info.length; i++)

                  if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                      return true;
                  }

          }
      }
  }catch (Exception e){}
    return false;

}