一、須要申請的權限
- android.permission.ACCESS_WIFI_STATE
- android.permission.CHANGE_WIFI_STATE
- android.permission.WAKE_LOCK
複製代碼
二、相關操做的代碼
- WifiManager wifi = (WifiManager) context
- .getSystemService(Context.WIFI_SERVICE);
- if (!wifi.isWifiEnabled()) { //若是wifi沒有開啓,則開啓。
- wifi.setWifiEnabled(true);
- }
- WifiConfiguration wc = new WifiConfiguration();
- wc.SSID = "\"SSID\""; //配置wifi的SSID,即該熱點的名稱,如:TP-link_xxx
- wc.preSharedKey = "\"password\""; //該熱點的密碼
- 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);
- Log.d("WifiPreference", "add Network returned " + res);
- boolean b = wifi.enableNetwork(res, true);
- Log.d("WifiPreference", "enableNetwork returned " + b);
複製代碼
三、注意 若是遇到force-close, 選wait便可, 由於啓動wifi須要幾秒鐘, UI若是5妙鍾還沒反映的話, 系統會給你這個force close exception