Sample code for Android WiFi hotspot development

  • 2021-11-10 11:01:48
  • OfStack

Last time, I wrote the content of Android connecting anonymous WiFi. WiFI development is a relatively small knowledge point for application layer development, but since it is used, it will be recorded here.

Create a hot spot

1. Create hot spots according to encryption type, password, whether to hide or not, etc.


 static WifiConfiguration createWifiConfig(String SSID, @WifiSecurityType int wifiCipherType, String password, boolean hiddenSSID) {

    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.SSID = convertToQuotedString(SSID);
    wifiConfiguration.hiddenSSID=hiddenSSID;// Whether to hide hot spots true= Hide , If hiding requires another device to manually add the network 
    switch (wifiCipherType) {
      case WifiSecurityType.SECURITY_NONE:
        wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        break;
      case WifiSecurityType.SECURITY_WEP:
        wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
        wifiConfiguration.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
        wifiConfiguration.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
        if (!TextUtils.isEmpty(password)) {
          int length = password.length();
          // WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
          if ((length == 10 || length == 26 || length == 58)
              && password.matches("[0-9A-Fa-f]*")) {
            wifiConfiguration.wepKeys[0] = password;
          } else {
            wifiConfiguration.wepKeys[0] = '"' + password + '"';
          }
        }
        break;

      case WifiSecurityType.SECURITY_WPA_PSK:
        wifiConfiguration.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
        if (!TextUtils.isEmpty(password)) {
          if (password.matches("[0-9A-Fa-f]{64}")) {
            wifiConfiguration.preSharedKey = password;
          } else {
            wifiConfiguration.preSharedKey = '"' + password + '"';
          }
        }
        break;

      case WifiSecurityType.SECURITY_WPA_EAP:
        wifiConfiguration.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
        wifiConfiguration.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
        wifiConfiguration.enterpriseConfig = new WifiEnterpriseConfig();
        int eapMethod = 0;
        int phase2Method = 0;
        wifiConfiguration.enterpriseConfig.setEapMethod(eapMethod);
        wifiConfiguration.enterpriseConfig.setPhase2Method(phase2Method);
        if (!TextUtils.isEmpty(password)) {
          wifiConfiguration.enterpriseConfig.setPassword(password);
        }
        break;
      default:
        break;
    }
    return wifiConfiguration;
  }

Then call the setWifiApEnabled method of WifiManager to set wifiConfiguration, because it is hidden and needs to be reflected:


 try {
      Method method = mWifManager.getClass().getMethod(
          "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
      boolean enable = (Boolean) method.invoke(mWifManager, config, true);

      if (enable) {
        Log.d("WiFi", " Hot spot has been turned on ");
      } else {
        Log.d("WiFi", " Failed to create hotspot ");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

Close hot spots

It is relatively simple to close the hot spot, and the above method is also used. The second parameter is passed to false:


public void closeWifiAp() {
    try {
      Method method = mWifiManager.getClass().getMethod("setWifiApEnabled",   WifiConfiguration.class, boolean.class);
      method.invoke(mWifiManager, null, false);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

Monitor hotspot status

The status of hot spots can be monitored by broadcasting:


 public static final String WIFI_AP_STATE_CHANGED_ACTION =
    "android.net.wifi.WIFI_AP_STATE_CHANGED";

However, this variable is hidden, and the broadcast can only be registered directly by value:


  IntentFilter filter = new IntentFilter();
    filter.addAction("android.net.wifi.WIFI_AP_STATE_CHANGED");

Then get state in the broadcast:


int state = intent.getIntExtra("wifi_state", 0);

wifi hotspots have the following states:


#WIFI_AP_STATE_DISABLED  
#WIFI_AP_STATE_DISABLING
#WIFI_AP_STATE_ENABLED
#WIFI_AP_STATE_ENABLING
#WIFI_AP_STATE_FAILED

Other API:

Get the current state of WiFI hotspot, and the return value is the above five states:


public int getWifiApState()

Determine whether the WiFi hotspot is open:


public boolean isWifiApEnabled()

Get the WifiConfiguration of the current wifi hotspot:


public WifiConfiguration getWifiApConfiguration()

Related articles: