android连接wifi模块

写在最前,项目中加了一个连接wifi的需求,在之前我是接了一下,发现在android10上wifimanger是不可以用了,需要使用新接口。但是这新接口接上去,连上wifi后没有数据。然后,就在昨天我又重新试了下,发现之前被抛弃的wifimanger这个接口又可以在android10上用了???而他给出的新接口还是一如既往的不能用。官方文档上现在记录的还是新接口,所以就不贴官方文档地址了,有兴趣的可以自己去翻。

在前面记一下遇到的问题和解决方法。

1. 华为手机无法连接保存过的无密码wifi,无法add上去。

解决方法是,在getConfiguredNetworks()接口里获取到对应ssid的networdId,然后直接连这个networkId。

2. 抄网上的博客时,无法连接无密码wifi。

删除掉如下代码

config.wepKeys[0] = "";
config.wepTxKeyIndex = 0;

 

下面贴一下,我的连接代码

@RequiresApi(api = Build.VERSION_CODES.O)
    private static boolean connect(String netWorkName, String password, Activity activity) {
        WifiManager wifiManager;
        wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        //获取系统保存的wifi信息
        List<WifiConfiguration> configurationInfos=wifiManager.getConfiguredNetworks();

        wifiManager.setWifiEnabled(true);
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();

        // 指定对应的SSID
        config.SSID = "\"" + netWorkName+ "\"";

        if(password.equals("")){
//            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
//            config.wepTxKeyIndex = 0;
        }else{
            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.allowedGroupCiphers.set(WifiConfiguration.GroupCipher .CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }

        int netId = wifiManager.addNetwork(config);
        
        if(netId==-1){
            for(WifiConfiguration wifiConfiguration : configurationInfos){
                if(config.SSID.equals(wifiConfiguration.SSID)){
                    netId = wifiConfiguration.networkId;
                }
            }
        }
        // 这个方法的第一个参数是需要连接wifi网络的networkId,第二个参数是指连接当前wifi网络是否需要断开其他网络
        boolean result = wifiManager.enableNetwork(netId, true);
        return result;
    }

传入账号密码就可以连接wifi了。

posted @ 2020-07-09 11:02  阿飞飞啊飞  阅读(1100)  评论(0编辑  收藏  举报