您好,登錄后才能下訂單哦!
項(xiàng)目開發(fā)中經(jīng)常會(huì)用到Wifi連接
Wifi連接分兩種情況有密碼和無(wú)密碼
一下兩種方法分別是連接有密碼和無(wú)密碼的方法
經(jīng)過小米2S和三星平板驗(yàn)證
//連接有密碼的Wifi
private void connectToWifi(String SSID, String key) {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "\"" + SSID + "\""; // wifi名稱
wc.preSharedKey = "\"" + key + "\""; // wifi密碼
wc.hiddenSSID = true;
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
int res = wifi.addNetwork(wc);
boolean b = wifi.enableNetwork(res, false);
}
//連接無(wú)密碼的Wifi
// 連接Wifi
private void connectToWifi(String SSID) {
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
//這個(gè)好像不太穩(wěn)定,之前可以連接有密碼的,現(xiàn)在又不行了,不清楚是什么原因
// config.wepKeys[0] = password; // 這里要注釋掉 因?yàn)檫B接的是沒有密碼的Wifi
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
wifiManager.enableNetwork(wifiManager.addNetwork(config), true);
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。