Android connect anonymous WiFi sample code

preface

Because the development needs to realize WiFi connection inside the application. Combined with online materials, it is still relatively simple to realize WiFi connection, but it is rarely mentioned to connect anonymous WiFi, so I share it here.

Basic use

First, introduce some basic concepts and tools related to WiFi development. Students who have been in contact with WiFi can skip the next section.

1. Authority

To use system functions in Android, you generally need to apply for permission. Here are the permissions required for WiFi

 <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
  <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> // 需要系统权限 [定位权限]

Because WiFi can be used for positioning, you need to apply for positioning permission here. For devices above 6.0, you need to actively apply for positioning permission.

2.API

The WiFi manager class is an API exposed by the framework layer to manage WiFi.

val mWifiManager = mContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

Through it, you can get: 1. List of configured networks. 2. WiFi currently connected. 3. Scanned WiFi. 4. And some constants indicate the intention of broadcasting, etc

Scanresult class is used to store WiFi scanning result information, mainly including the following contents:

3. Change of WiFi status of monitoring device

The change of WiFi status will lead to broadcast events.

val filter = IntentFilter()
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION) //监听wifi状态改变
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) //监听扫描到wifi列表改变

private val mReceiver = object : BroadcastReceiver() {

    override fun onReceive(context: Context,intent: Intent) {
      val action = intent.action
      if (TextUtils.isEmpty(action)) return
      when (action) {
        WifiManager.WIFI_STATE_CHANGED_ACTION -> {

        }
        WifiManager.SCAN_RESULTS_AVAILABLE_ACTION -> {

        }
      }
    }
  }

There are enum types in the current status in the WiFi manager, as shown in the following table:

Connect to normal WiFi

Connecting WiFi can be divided into the following steps:

public static void connectNewWifi(Context mContext,WifiConfiguration wifiConfiguration) {

    WifiManager wifiManager = (WifiManager) mContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    int networkId = wifiManager.addNetwork(wifiConfiguration);
    wifiManager.enableNetwork(networkId,true);

  }

Therefore, the key point is how to create WiFi configuration. The creation process of WiFi with different encryption methods is also different:

 public WifiConfiguration createWifiConfig(String SSID,@WifiCipherType int wifiCipherType,String password) {
    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.SSID = convertToQuotedString(SSID);

    switch (wifiCipherType) {
      case WifiCipherType.Security_NONE:
        wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        break;
      case WifiCipherType.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 WifiCipherType.Security_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 WifiCipherType.Security_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;
  }

At this point, the WiFi connection is completed, and then the connection results can be obtained in the broadcast. The corresponding WiFi configuration information will be saved in / data / misc / WiFi / WPA_ In supplicant.conf:

network={
    ssid="test"
    psk="88888888"
    key_mgmt=WPA-PSK
    disabled=1
    id_str="%7B%22creatorUid%22%3A%221000%22%2C%22configKey%22%3A%22%5C%22test%5C%22WPA_PSK%22%7D"
}

Connect anonymous WiFi

Compared with ordinary WiFi, anonymous WiFi does not broadcast its SSID, so it cannot be scanned directly. We need to enter the WiFi SSID to actively scan. Let's take a look at the configuration information of anonymous WiFi first:

network={
    ssid="test2"
    scan_ssid=1
    bssid=56:28:f8:fa:f8:a0
    psk="44444444"
    key_mgmt=WPA-PSK
    disabled=1
    id_str="%7B%22creatorUid%22%3A%221000%22%2C%22configKey%22%3A%22%5C%22test2%5C%22WPA_PSK%22%7D"
} 

As you can see, there is an additional scan_ SSID property. Check the WiFi configuration. There is indeed a property that can be set

/**
   * This is a network that does not broadcast its SSID,so an
   * SSID-specific probe request must be used for scans.
   */
  public boolean hiddenSSID;

Therefore, when creating WiFi configuration, just set this attribute:

configuration.hiddenSSID = true

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>