Android的连接到无线网络,无需人工互动互动、连接到、无线网络、Android

2023-09-05 07:00:38 作者:欧霸

我不知道是否有可用于Android设备连接到WiFi网络,一些code片段。该网络应该是开放或WEP / WPA已加密,并且可见,给该设备。通常情况下,我们使用的GUI界面输入无线网络密码,然后点击连接按钮。我要存储密码的地方,并使用密码连接到网络的无缝连接,无​​需人工交互。那可能吗?非常感谢。

I'm wondering if there are some code snippets that can be used to connect an Android device to a WiFi network. The network should be either open or WEP/WPA encypted, and visible to that device. Normally, we use GUI interface to input WiFi passwords and tap the connect button. I want to store the password in a place, and use the password to connect to the network seamlessly without human interaction. Is that possible? Thanks a lot.

推荐答案

谢谢你们。有了您的帮助,我现在可以连接到WPA / PSK加密的网络无疼痛。这是我的code片断:

Thanks guys. With your help, I'm now able to connect to a WPA/PSK encrypted network without pain. Here is my code snippet:

        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()方法启用它。