安卓开发-WIFI模块开发

本文详细介绍了如何在Android应用中获取Wi-Fi信息,包括通过WifiManager获取和处理WiFi扫描结果,连接保存或未保存的WiFi,以及监听WiFi状态变化、密码验证等。同时涵盖了Wi-Fi广播的设置和接收机制。
摘要由CSDN通过智能技术生成

一、wifi信息的获取设置;

1.1 WifiManager获取

wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

1.2 WifiInfo获取

wifiInfo = wifiManager.getConnectionInfo();

1.3 wifi扫面(耗时操作,建议放在子线程中去执行)

wifiManager.startScan();
                List<ScanResult> list = wifiManager.getScanResults();
                if (list == null) {
                    Log.d(TAG, "startScan: wifilist=null");
                    if (wifiManager.getWifiState() == 3) {
                        Toast.makeText(context.getApplicationContext(), "当前区域没有无线网络", Toast.LENGTH_SHORT).show();
                    } else if (wifiManager.getWifiState() == 2) {
                        Toast.makeText(context.getApplicationContext(), "WiFi正在开启,请稍后重新点击扫描", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context.getApplicationContext(), "WiFi没有开启,无法扫描", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Log.d(TAG, "startScan: list: " + list.size());
                    //去重
                    List<ScanResult> newList = new ArrayList<>();
                    int count = -1;
                    HashMap<String, Integer> signalStrength = new HashMap<String, Integer>();
                    for (int i = 0; i < list.size(); i++) {
                        ScanResult scanResult = list.get(i);
                        if (!scanResult.SSID.isEmpty()) {
                            String key = scanResult.SSID + " " + scanResult.capabilities;
                            if (!signalStrength.containsKey(key)) {
                                count++;
                                signalStrength.put(key, count);
                                newList.add(scanResult);
                            } else {
                                int position = signalStrength.get(key);
                                ScanResult updateScan = newList.get(position);
                                if (updateScan.level > scanResult.level) {
                                    newList.set(position, updateScan);
                                }
                            }
                        }
                    }
                    Log.d(TAG, "startScan: newlist: " + newList.size());
                    //添加已保存wifi识别
                    getWifiConfigurationList();
                    for (int i = 0; i < newList.size(); i++) {
                        ScanResult scanResult = newList.get(i);
                        WifiBean wifiBean = new WifiBean();
                        wifiBean.setScanResult(scanResult);
                        String capabilities = scanResult.capabilities.trim();
                        Log.d(TAG, "startScan: scanResult...SSID: " + scanResult.SSID
                                + "  BSSID: " + scanResult.BSSID
                                + "  capabilities: " + capabilities);
                        String ssid = scanResult.SSID;
                        wifiBean.setNetId(isWifiConfig(ssid));
                        wifiBean.setNeedPsw(capabilities.contains("WEP") || capabilities.contains("WPA"));
                        wifiList.add(wifiBean);
                    }
                    //排序
                    levelSort(wifiList);
                    ThreadManager.getInstance().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (scanFinishLis != null) {
                                scanFinishLis.onWifiScanFinish();
                            }
                        }
                    });
                    Log.d(TAG, "startScan: wifiList: " + wifiList.size());
                }
/**
     * 获取已保存的wifi的列表
     */
    @SuppressLint("MissingPermission")
    private void getWifiConfigurationList() {
        wifiConfigurationList.clear();
        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        if (list != null && !list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                WifiConfiguration config = list.get(i);
//                Log.d(TAG, "getWifiConfigurationList: 111: "+config.SSID + " password: "+config.preSharedKey + " netid: "+config.networkId);
                if (!isConfigListHave(config.SSID)) {
                    wifiConfigurationList.add(config);
                }
            }
        }
        if (wifiConfigurationList == null) {
            Log.d(TAG, "startScan: wifiConfigurationList == null");
        } else {
            Log.d(TAG, "startScan: wifiConfigurationList: " + wifiConfigurationList.size());
            for (int i = 0; i < wifiConfigurationList.size(); i++) {
                Log.d(TAG, "getWifiConfigurationList: ssid: " + wifiConfigurationList.get(i).SSID
                        + " preSharedKey: " + wifiConfigurationList.get(i).preSharedKey
                        + " networkId: " + wifiConfigurationList.get(i).networkId
                        + " status: " + wifiConfigurationList.get(i).status
                );
            }
        }
    }
/**
     * 按信号强度排序
     */
    private void levelSort(List<WifiBean> list) {
        Collections.sort(list, new Comparator<WifiBean>() {
            @Override
            public int compare(WifiBean o1, WifiBean o2) {
                return o2.getScanResult().level - o1.getScanResult().level;
            }
        });
    }

1.4 连接wifi(分已保存未保存,有密码无密码)

public void connectWifi(String ssid, String password) {
        Log.d(TAG, "connectWifi: ssid: " + ssid + "  password: " + password);
        // 创建一个新的WiFi配置
        WifiConfiguration wifiConfig = new WifiConfiguration();
        wifiConfig.SSID = "\"" + ssid + "\"";
        if (TextUtils.isEmpty(password)) {  //无需输入密码的wifi
            wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        } else {  //需要输入密码连接的WiFi
            wifiConfig.preSharedKey = "\"" + password + "\"";
        }
        // 添加新的WiFi配置并连接到它
        connectNetid = wifiManager.addNetwork(wifiConfig);
        wifiManager.disconnect();
        boolean isSuccess = wifiManager.enableNetwork(connectNetid, true);
        Log.d(TAG, "addNetwork: isSuccess: " + isSuccess + "  netId: " + connectNetid);
        wifiManager.reconnect();
    }
public void connectConfigedWifi(int netId) {
        Log.d(TAG, "connectConfigedWifi: netId: " + netId);
        connectNetid = netId;
        wifiManager.disconnect();
        boolean isSuccess = wifiManager.enableNetwork(netId, true);
        Log.d(TAG, "connectConfiguration: isSuccess: " + isSuccess);
        wifiManager.reconnect();
    }

1.5 断开wifi连接

/**
     * 断开连接
     */
    private void disConnect(int netId) {
        wifiManager.disableNetwork(netId);
        boolean isSuccess = wifiManager.disconnect();
        Log.d(TAG, "disConnect...isSuccess: " + isSuccess);
    }

1.6 判断wifi是否连接

/**
     * wifi是否已连接
     * 注:wifi状态改变后如果立即判断wifi状态,会拿到错误的状态;需作延迟;为避免带来其他问题,此方法尽少使用
     */
    @Override
    public boolean isWifiConnect() {
        ConnectivityManager connManager = (ConnectivityManager) InitManager.getInstance().mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        @SuppressLint("MissingPermission")
        NetworkInfo mWifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifiInfo.isConnected();
    }

1.7 打开WiFi

public void openWifi() {
        if (!wifiManager.isWifiEnabled()) {
            boolean isSuccess = wifiManager.setWifiEnabled(true);
            Log.d(TAG, "openWifi: isSuccess: " + isSuccess);
        } else if (wifiManager.getWifiState() == 2) {
            Log.d(TAG, "openWifi: 正在开启中");
        } else {
            Log.d(TAG, "openWifi: 已经开启了");
        }
    }

1.8 关闭WiFi

public void closeWifi() {
        if (wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
        } else if (wifiManager.getWifiState() == 1) {
            Log.d(TAG, "openWifi: 已经关闭了");
        } else if (wifiManager.getWifiState() == 0) {
            Log.d(TAG, "openWifi: 正在关闭中");
        } else {
            Log.d(TAG, "openWifi: 需重新关闭");
        }
    }

1.9 获取连接wifi的ip地址

public String getStringIpAddress() {
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ip = wifiInfo.getIpAddress();
        return String.format("%d.%d.%d.%d", (ip & 0xff), (ip >> 8 & 0xff), (ip >> 16 & 0xff), (ip >> 24 & 0xff));
    }

1.10 获取wifi信号强度

public int getConnectWifiStrength() {
        Log.d(TAG, "getConnectWifiStrength: ");
        WifiInfo info = wifiManager.getConnectionInfo();
        if (info != null && info.getBSSID() != null) {
            int rssi = info.getRssi();
            Log.d(TAG, "getConnectWifiStrength: rssi: " + rssi);
            return WifiManager.calculateSignalLevel(rssi, 5);
        }
        return -1;
    }

二、WIFI广播的监听

主要监听有:
1、wifi开启和关闭通知
2、wifi网络连接状态改变通知
3、校验wifi密码是否正确通知

IntentFilter filter = new IntentFilter();//创建filter实例
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);  //wifi开启状态监听
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);//WiFi连接状态监听
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);//验证密码监听   没有效果暂时隐藏
        context.registerReceiver(wifiReceiver, filter);

receivce逻辑处理:

if (action != null) {
            switch (action) {
                case WifiManager.WIFI_STATE_CHANGED_ACTION:
                    int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1);
                    switch (wifiState) {
                        case WifiManager.WIFI_STATE_ENABLED:  //监控wifi开启和关闭
                            Log.d(TAG, "onReceive: wifi已开启");
                            if (iWifiLis != null) {
                                iWifiLis.wifiOpen();
                            }
                            break;
                        case WifiManager.WIFI_STATE_DISABLED:
                            Log.d(TAG, "onReceive: wifi已关闭");
                            if (iWifiLis != null) {
                                iWifiLis.wifiClose();
                            }
                            break;
                        default:
                            break;
                    }
                    break;
                case WifiManager.NETWORK_STATE_CHANGED_ACTION:  //监控wifi网络连接状态
                    NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                    NetworkInfo.State state = networkInfo.getState();
                    Log.d(TAG, "onReceive: wifi连接状态...state: " + state);
                    if (iWifiLis != null) {
                        if (state == NetworkInfo.State.CONNECTED) {
                            iWifiLis.wifiConnectState(true);
                        } else if (state == NetworkInfo.State.DISCONNECTED) {
                            iWifiLis.wifiConnectState(false);
                        }
                    }
                    break;
                case WifiManager.SUPPLICANT_STATE_CHANGED_ACTION:
                    // 检查Supplicant状态变化
//                    SupplicantState supplicantState = intent.getParcelableExtra(WifiManager.EXTRA_SUPPLICANT_STATE);
                    SupplicantState supplicantState = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
                    Log.d(TAG, "onReceive: supplicantState: " + supplicantState);
                    if (supplicantState == SupplicantState.COMPLETED) {
                        // wifi连接成功
                    } else if (supplicantState == SupplicantState.DISCONNECTED) {
                        Log.d(TAG, "onReceive: DISCONNECTED");
                        if (System.currentTimeMillis() - regTime < 1000) {
                            Log.d(TAG, "onReceive: 刚进入wifi界面注册上广播,就收到密码异常返回,此现象不做处理");
                            return;
                        }
                        // 检查是否包含AUTHENTICATING状态,可能是因为密码错误
//                        boolean hasAuthError = intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, false);
                        int hasAuthError = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 123);
                        Log.d(TAG, "onReceive: hasAuthError: " + hasAuthError);
                        if (hasAuthError == WifiManager.ERROR_AUTHENTICATING) {  // WiFi验证错误
                            int errorReason = intent.getIntExtra("supplicantErrorReason", 0);
                            Log.d(TAG, "onReceive: errorReason: " + errorReason);
                            if (errorReason <= 3) { //wifi密码错误
                                Toast.makeText(context, "WIFI密码错误", Toast.LENGTH_SHORT).show();
                            } else {  //其他问题导致连接失败
                                Toast.makeText(context, "wifi连接失败,请重试", Toast.LENGTH_SHORT).show();
                            }
                            com.iflytek.autofly.lib_repo.manager.WifiManager.getInstance().connectWifiError();
                        }
                    }
                    break;
            }

        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值