android 连接wifi

来源:互联网 发布:ubuntu查看显卡使用率 编辑:程序博客网 时间:2024/06/05 10:03

前几天在做一个远程控制app用来获取远端设备wifi列表并控制远端设备连接wifi,做下简单记录,主要代码如下:


//创建一个WifiConfiguration

public WifiConfiguration createWifiInfo(ScanResult scan, String password) {    WifiConfiguration config = new WifiConfiguration();    config.hiddenSSID = false;    config.SSID="\"" + scan.SSID + "\"";    config.status = WifiConfiguration.Status.ENABLED;    DLogUtils.e(TAG,"capabilities : "+scan.capabilities+" ,ssid : "+config.SSID);    if (scan.capabilities.contains("WEP")) {        DLogUtils.e(TAG,"createWifiInfo 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;    } else if (scan.capabilities.contains("WPA")) {        DLogUtils.e(TAG,"createWifiInfo WPA ");        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;    }else {        DLogUtils.e(TAG,"createWifiInfo else ");        config.allowedAuthAlgorithms.clear();        config.allowedGroupCiphers.clear();        config.allowedKeyManagement.clear();        config.allowedPairwiseCiphers.clear();        config.allowedProtocols.clear();        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);    }    return config;}

//添加网络

int networkId = wifiManager.addNetwork(createWifiInfo(sr,wifi_password));

//连接网络

private boolean connectToWifi(int netId){    boolean enableNetwork = wifiManager.enableNetwork(netId, true);    DLogUtils.e(TAG,"connectToWifi netId : "+netId+" ,enableNetwork : "+enableNetwork);    return enableNetwork;}



原创粉丝点击