您好,登錄后才能下訂單哦!
項目開發中經常會用到Wifi連接
Wifi連接分兩種情況有密碼和無密碼
一下兩種方法分別是連接有密碼和無密碼的方法
經過小米2S和三星平板驗證
//連接有密碼的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);
}
//連接無密碼的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 + "\"";
//這個好像不太穩定,之前可以連接有密碼的,現在又不行了,不清楚是什么原因
// config.wepKeys[0] = password; // 這里要注釋掉 因為連接的是沒有密碼的Wifi
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
wifiManager.enableNetwork(wifiManager.addNetwork(config), true);
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。