我想知道是否有一些代码 fragment 可用于将 Android 设备连接到 WiFi 网络。网络应该是开放的或 WEP/WPA 加密的,并且对该设备可见。通常,我们使用 GUI 界面输入 WiFi 密码并点击连接按钮。我想将密码存储在一个地方,并使用密码无缝连接到网络,无需人工干预。那可能吗?非常感谢。
最佳答案
谢谢大家。在您的帮助下,我现在可以轻松连接到 WPA/PSK 加密网络。这是我的代码 fragment :
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// setup a wifi configuration
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "\"YOUR_SSID\"";
wc.preSharedKey = "\"YOUR_PASSWORD\"";
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);
// connect to and enable the connection
int netId = wifiManager.addNetwork(wc);
wifiManager.enableNetwork(netId, true);
wifiManager.setWifiEnabled(true);
技巧是:
- SSID字符串用"包围,用\"表示
- addNetwork() 方法默认禁用添加的网络,因此您应该使用 enableNetwork() 方法启用它。
关于Android无需人工交互即可连接WiFi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6141185/