Wifi连接与使用

Posted zhoujianan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Wifi连接与使用相关的知识,希望对你有一定的参考价值。

1.Manifest.xm配置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.WAKE_LOCK" />
<uses-permission android:name="android.permission.FORCE_STOP_PACKAGES" />
<uses-permission android:name="android.permission.MASTER_CLEAR" />
<uses-permission android:name="android.permission.CAMERA" />

2.打开wifi

public void openWifi() {
        if (!mWifiManager.isWifiEnabled()) {
             mWifiManager.setWifiEnabled(true);
    }
}

3.进行扫描

 public boolean startScan() {
        return mWifiManager.startScan();
    }

4.注册监听并通过返回刷新WiFiList

        IntentFilter wifiFilter = new IntentFilter();
        wifiFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        wifiFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        wifiFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        wifiFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        registerWifiReceiver(wifiFilter);

    public void registerWifiReceiver(IntentFilter intentFilter) {
        if (null == wifiReceiver) {
            wifiReceiver = new WifiReceiver();
        }
        mContext.registerReceiver(wifiReceiver, intentFilter);
    }

5.监听网络变化

    class WifiReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "onReceive: intent action" + intent.getAction());
            if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
          //当扫描结果后,进行刷新列表 refreshLocalWifiListData(); if (null != listener) { listener.onScanResultAvailable(); } } else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {//wifi连接网络状态变化 refreshLocalWifiListData(); NetworkInfo.DetailedState state = ((NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO)).getDetailedState(); if (null != listener) { listener.onNetWorkStateChanged(state, mSSID); } } else if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {//wifi状态变化 int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED); if (null != listener) { listener.onWiFiStateChanged(wifiState); } } else if (intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) { SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE); int error = intent.getIntExtra(EXTRA_SUPPLICANT_ERROR, 0); if (null != listener) { if (error == WifiManager.ERROR_AUTHENTICATING) {
              //这里可以获取到监听连接wifi密码错误的时候进行回调 listener.onWifiPasswordFault(); } } } } }

6.刷新wifi列表

    public void refreshLocalWifiListData() {
//逻辑说明:
1.从扫描结果中将已经连接的wifi添加到wifi列表中
2.从所有WiFilist中将已经添加过的已经连接的WiFi移除
3.将剩余的WiFi添加到WiFilist中
实现了已经连接的WiFi处于wifi列表的第一位


        //得到扫描结果
        mWifiList.clear();
        List<ScanResult> tmpList = mWifiManager.getScanResults();
        for (ScanResult tmp : tmpList) {
            if (isGivenWifiConnect(tmp.SSID)) {
                mWifiList.add(tmp);
            }
        }
        //从wifi列表中删除已经连接的wifi
        for (ScanResult tmp : mWifiList) {
            tmpList.remove(tmp);
        }
       mWifiList.addAll(tmpList);
        }

    }

7.进行WiFi连接

  wifi连接的方式:1.WiFi configuration 2.将其添加到网络中。

  第一步:

 public WifiConfiguration creatWifiConfiguration(String ssid, String password) {
        ScanResult currentWIFI = null;
        WifiSecutityEnum type = WifiSecutityEnum.NOON;
        for (ScanResult temp : getmWifiList()) {
            if (temp.SSID.equals(ssid)) {
                currentWIFI = temp;
            }
        }
        if (currentWIFI != null) {
            Log.i(TAG, "creatWifiConfiguration: " + currentWIFI.toString());
            type = getWifiSecurityMode(currentWIFI.capabilities);
        }

        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = """ + ssid + """;
        //如果当前连接的wifi被保存了密码,清除wifi保存信息
        WifiConfiguration tempConfig = isWifiSave(ssid);
        if (tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
            mWifiManager.saveConfiguration();
        }

        switch (type) {
            case NOON:
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                break;
            case WEP:
                config.hiddenSSID = true;
                config.wepKeys[0] = """ + password + """;
                config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                config.wepTxKeyIndex = 0;
                break;
            case WPA_AND_WPA2:
                config.preSharedKey = """ + password + """;
                config.hiddenSSID = true;
                config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                config.status = WifiConfiguration.Status.ENABLED;
                break;
        }
        return config;
    }

//如果之前有连接过WiFi,可以进行保存或者不进行保存
/**
* 判断指定的wifi是否保存
*
* @param SSID
* @return
*/
public WifiConfiguration isWifiSave(String SSID) {
if (mWifiConfigurations != null) {
for (WifiConfiguration existingConfig : mWifiConfigurations) {
if (existingConfig.SSID.equals(""" + SSID + """)) {
return existingConfig;
}
}
}
return null;
}


  第二步:

    public void connect(WifiConfiguration config) {
        int wcgID = mWifiManager.addNetwork(config);
        mWifiManager.enableNetwork(wcgID, true);
    }

 

第三步:监听当前是否已经连接到网络

//判断当前是否已经连接  
 public boolean isGivenWifiConnect(String SSID) {
        return isWifiConnected() && getCurentWifiSSID().equals(SSID);
    }

//得到当前连接的WiFi  SSID
    public String getCurentWifiSSID() {
        String ssid = "";
        ssid = mWifiManager.getConnectionInfo().getSSID();
        if (ssid.substring(0, 1).equals(""")
                && ssid.substring(ssid.length() - 1).equals(""")) {
            ssid = ssid.substring(1, ssid.length() - 1);
        }
        return ssid;
    }
  /**
     * 是否处于wifi连接的状态
     *
     */
    public boolean isWifiConnected() {
        NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetworkInfo.isConnected()) {
            return true;
        } else if (wifiNetworkInfo.isAvailable()) {
            return true;
        }

        return false;
    }

 8.监听WifiConnect的状态

public void onNetWorkStateChanged(NetworkInfo.DetailedState state) {
        if (state == NetworkInfo.DetailedState.SCANNING) {
            Log.i(TAG, "onReceive onNetWorkStateChanged: +正在扫描");
            mainView.showWifiConnectInfo("正在扫描");
        } else if (state == NetworkInfo.DetailedState.CONNECTING) {
            Log.i(TAG, "onReceive onNetWorkStateChanged: +正在连接");
            mainView.showWifiConnectInfo("正在连接");

        } else if (state == NetworkInfo.DetailedState.OBTAINING_IPADDR) {
            Log.i(TAG, "onReceive onNetWorkStateChanged: +获取IP地址");
            mainView.showWifiConnectInfo("获取IP地址");

        } else if (state == NetworkInfo.DetailedState.CONNECTED) {
            Log.i(TAG, "onReceive onNetWorkStateChanged: +建立连接");
            mainView.showWifiConnectInfo("建立连接");

        } else if (state == NetworkInfo.DetailedState.DISCONNECTING) {
            Log.i(TAG, "onReceive onNetWorkStateChanged: +正在断开连接");
            mainView.showWifiConnectInfo("正在断开连接");

        } else if (state == NetworkInfo.DetailedState.DISCONNECTED) {
            Log.i(TAG, "onReceive onNetWorkStateChanged: +已断开连接");
            mainView.showWifiConnectInfo("已断开连接");

        } else if (state == NetworkInfo.DetailedState.FAILED) {
            Log.i(TAG, "onReceive onNetWorkStateChanged: +连接失败");
            mainView.showWifiConnectInfo("连接失败");

        }
//同时可以更新view的列表
        mainView.updateWifiListView();
    }

  9.断开连接

 public void disConnectWifi(){
        mWifiManager.disconnect();
    }

 //断开指定ID的网络
 public void disConnectionWifi(int netId) {
        mWifiManager.disableNetwork(netId);
        mWifiManager.disconnect();
    }

  

 





























以上是关于Wifi连接与使用的主要内容,如果未能解决你的问题,请参考以下文章

安装centos之后添加win7引导的代码与连接wifi

C#WIFI搜索与连接

wifi模块怎样与单片机连接?

Wifi连接与使用

ADB使用WIFI连接Android设备

苹果为啥弹出与别人共享wifi