Android WIFI功能——WifiManager

个人博客:haichenyi.com。感谢关注

  之前做了关于Android wifi的相关功能,这里做一个记录

第一步:获取WifiManager

WifiManager wifiMgr = (WifiManager)Context.getSystemService(Context.WIFI_SERVICE);

第二步:获取周围热点信息和已连接wifi信息

List<ScanResult> scanResults = wifiMgr.getScanResults();//扫描到的周围热点信息
WifiInfo info = wifiMgr.getConnectionInfo();//已连接wifi信息

这里我说一下几个字段的意思:

  public String name;//ssid对应的wifi名字
  public String capabilities;//用来判断是否有密码
  public int level;//信号等级,这里是负数
  public String BSSID;//macid

这里我需要强调的就是level,是负数,负数越大,信号越好

第三步:检测wifi信息,这里我给出几个工具类

/**
   * 连接有密码的wifi.
   *
   * @param SSID     ssid
   * @param Password Password
   * @return apConfig
   */
  private WifiConfiguration setWifiParamsPassword(String SSID, String Password) {
    WifiConfiguration apConfig = new WifiConfiguration();
    apConfig.SSID = "\"" + SSID + "\"";
    apConfig.preSharedKey = "\"" + Password + "\"";
    //不广播其SSID的网络
    apConfig.hiddenSSID = true;
    apConfig.status = WifiConfiguration.Status.ENABLED;
    //公认的IEEE 802.11验证算法。
    apConfig.allowedAuthAlgorithms.clear();
    apConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    //公认的的公共组密码
    apConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    apConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    //公认的密钥管理方案
    apConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    //密码为WPA。
    apConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    apConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    //公认的安全协议。
    apConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    return apConfig;
  }
  
  /**
   * 连接没有密码wifi.
   *
   * @param ssid ssid
   * @return configuration
   */
  private WifiConfiguration setWifiParamsNoPassword(String ssid) {
    WifiConfiguration configuration = new WifiConfiguration();
    configuration.SSID = "\"" + ssid + "\"";
    configuration.status = WifiConfiguration.Status.ENABLED;
    configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    configuration.allowedPairwiseCiphers
        .set(WifiConfiguration.PairwiseCipher.TKIP);
    configuration.allowedPairwiseCiphers
        .set(WifiConfiguration.PairwiseCipher.CCMP);
    configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    return configuration;
  }
  
  public static final int WIFI_NO_PASS = 0;
  private static final int WIFI_WEP = 1;
  private static final int WIFI_PSK = 2;
  private static final int WIFI_EAP = 3;
  
  /**
   * 判断是否有密码.
   *
   * @param result ScanResult
   * @return 0
   */
  public static int getSecurity(MyScanResult result) {
    if (null != result && null != result.capabilities) {
      if (result.capabilities.contains("WEP")) {
        return WIFI_WEP;
      } else if (result.capabilities.contains("PSK")) {
        return WIFI_PSK;
      } else if (result.capabilities.contains("EAP")) {
        return WIFI_EAP;
      }
    }
    return WIFI_NO_PASS;
  }

上面三个工具类,一个用来判断是否需要密码,另外两个用来连接wifi

连接wifi

//需要密码
wifiMgr.enableNetwork(wifiMgr.addNetwork(
                    setWifiParamsPassword(mClickResult.name, password)), true);
//不需要密码
wifiMgr.enableNetwork(wifiMgr.addNetwork(setWifiParamsNoPassword(mClickResult.name)),
              true);

wifi监听

PS:关于wifi状态的监听,就是监听你当前的网络状态即可。

<receiver android:name=".receiver.NetworkReceiver">
            <intent-filter>
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
                <action android:name="android.net.wifi.STATE_CHANGE"/>
                <action android:name="android.net.wifi.supplicant.STATE_CHANGE"/>
                <action android:name="android.net.wifi.NETWORK_IDS_CHANGED"/>
            </intent-filter>
        </receiver>

首先在你的清单文件注册这四种action的广播,这里给出我的网络监听广播

/**
 * Author: 海晨忆.
 * Date: 2018/1/10
 * Desc: 网络广播监听
 */
public class NetworkReceiver extends BroadcastReceiver {
  public static final int STATE1 = 1;//密码错误
  public static final int STATE2 = 2;//连接成功
  public static final int STATE3 = 3;//连接失败
  public static final int STATE4 = 4;//正在获取ip地址
  public static final int STATE5 = 5;//正在连接

  @Override
  public void onReceive(Context context, Intent intent) {
    if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(intent.getAction())) {
      //密码错误广播,是不是正在获得IP地址
      int linkWifiResult = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -1);
      if (linkWifiResult == WifiManager.ERROR_AUTHENTICATING) {
        //密码错误
        ToastUtils.showTipMsg(R.string.password_wrong);
        sendNetworkStateChange(new NetWorkInfo().setState(STATE1));
      }
      SupplicantState supplicantState = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
      NetworkInfo.DetailedState state = WifiInfo.getDetailedStateOf(supplicantState);
      Log.v(Constants.HTTP_WZ, state.name());
      if (state == NetworkInfo.DetailedState.CONNECTING) {
        //正在连接
        ToastUtils.showTipMsg(R.string.linking);
        sendNetworkStateChange(new NetWorkInfo().setState(STATE5));
      } else if (state == NetworkInfo.DetailedState.FAILED
          || state == NetworkInfo.DetailedState.DISCONNECTING) {
        //连接失败
        sendNetworkStateChange(new NetWorkInfo().setState(STATE3));
        ToastUtils.showTipMsg(R.string.linked_failed);
      } else if (state == NetworkInfo.DetailedState.CONNECTED) {
        //连接成功
        ToastUtils.showTipMsg(R.string.linked_success);
      } else if (state == NetworkInfo.DetailedState.OBTAINING_IPADDR) {
        //正在获取ip地址
        sendNetworkStateChange(new NetWorkInfo().setState(STATE4));
      } else if (state == NetworkInfo.DetailedState.IDLE) {
        //闲置的
        ConnectivityManager connectManager = (ConnectivityManager) BaseApplication.getInstance()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = null;
        if (connectManager != null) {
          activeNetworkInfo = connectManager.getActiveNetworkInfo();
        }
        if (activeNetworkInfo == null) {
          sendNetworkStateChange(new NetWorkInfo().setState(STATE3));
          ToastUtils.showTipMsg(R.string.linked_failed);
        }
      }
    } else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
      // 监听wifi的打开与关闭,与wifi的连接无关
      int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
      Log.v(Constants.HTTP_WZ, "wifiState:" + wifiState);
      switch (wifiState) {
        case WifiManager.WIFI_STATE_DISABLING://正在停止0
          ToastUtils.showTipMsg(R.string.close_wifi);
          break;
        case WifiManager.WIFI_STATE_DISABLED://已停止1
          break;
        case WifiManager.WIFI_STATE_UNKNOWN://未知4
          break;
        case WifiManager.WIFI_STATE_ENABLING://正在打开2
          ToastUtils.showTipMsg(R.string.opening_wifi);
          break;
        case WifiManager.WIFI_STATE_ENABLED://已开启3
          break;
        default:
          break;
      }
    } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
      // 监听wifi的连接状态即是否连上了一个有效无线路由
      Parcelable parcelableExtra = intent
          .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
      if (null != parcelableExtra) {
        // 获取联网状态的NetWorkInfo对象
        NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
        //获取的State对象则代表着连接成功与否等状态
        NetworkInfo.State state = networkInfo.getState();
        //判断网络是否已经连接
        boolean isConnected = state == NetworkInfo.State.CONNECTED;
        Log.v(Constants.HTTP_WZ, "isConnected:" + isConnected);
        if (isConnected) {
          ToastUtils.showTipMsg(R.string.linked_success);
          sendNetworkStateChange(new NetWorkInfo().setState(STATE2));
        }
      }
    }
  }

  /**
   * 发送网络状态eventBus.
   *
   * @param info info
   */
  private void sendNetworkStateChange(NetWorkInfo info) {
    EventBus.getDefault().post(info);
  }

  @SuppressWarnings("unused")
  private String getConnectionType(int type) {
    String connType = "";
    if (type == ConnectivityManager.TYPE_MOBILE) {
      connType = "移动网络";
    } else if (type == ConnectivityManager.TYPE_WIFI) {
      connType = "WIFI网络";
    }
    return connType;
  }

  public static class NetWorkInfo {
    public int state;//1密码错误,2:连接成功,3:连接失败

    private NetWorkInfo setState(int state) {
      this.state = state;
      return this;
    }
  }
}

注释应该写的很清楚,我就不做过多的解释了。

    原文作者:海晨忆
    原文地址: https://www.jianshu.com/p/4b59ca68b994
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞