安卓6:以编程方式连接特定的wifi网络无法正常工作

5

我正在尝试使用WifiManager配置连接到wifi网络,通过提供SSID和密码来实现。

根据此线程的解决方案: 如何在Android中以编程方式连接到特定的Wi-Fi网络?

调用了重新连接方法,但没有任何反应(未连接)。

是Android版本(6.0.1)有问题吗? 如果是,则如何在Android 6上以编程方式执行网络连接?


你解决了吗? - SKK
7个回答

12

自从Android Marshmallow系统以来,连接WiFi网络的方式发生了一些变化。以下代码将帮助您... 如果您正在使用Android 6.0或低版本...

public void connectToWifi(){
    try{
        WifiManager wifiManager = (WifiManager) super.getSystemService(android.content.Context.WIFI_SERVICE);
        WifiConfiguration wc = new WifiConfiguration();
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        wc.SSID = "\"NETWORK_NAME\"";
        wc.preSharedKey = "\"PASSWORD\"";
        wc.status = WifiConfiguration.Status.ENABLED;
        wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

        wifiManager.setWifiEnabled(true);
        int netId = wifiManager.addNetwork(wc);
        if (netId == -1) {
            netId = getExistingNetworkId(wc.SSID);
        }
        wifiManager.disconnect();
        wifiManager.enableNetwork(netId, true);
        wifiManager.reconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
private int getExistingNetworkId(String SSID) {
    WifiManager wifiManager = (WifiManager) super.getSystemService(Context.WIFI_SERVICE);
    List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
    if (configuredNetworks != null) {
        for (WifiConfiguration existingConfig : configuredNetworks) {
            if (existingConfig.SSID.equals(SSID)) {
                return existingConfig.networkId;
            }
        }
    }
    return -1;
}

并在清单文件中添加权限。

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

3
使用addNetwork添加wifi配置,然后使用enableNetwork连接到它。
    WifiConfiguration wificonfiguration = new WifiConfiguration();
    StringBuffer stringbuffer = new StringBuffer("\"");
    stringbuffer.append((new StringBuilder(String.valueOf(HOTSPOT_NAME))).append("\"").toString());
    wificonfiguration.SSID = stringbuffer.toString();
    wificonfiguration.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
    wificonfiguration.allowedAuthAlgorithms.set(0);
    wificonfiguration.status = 2;
    wificonfiguration.preSharedKey = "\"" + HOTSPOT_PASSWORD + "\"";

    int networkId_ = wifi.addNetwork(wificonfiguration);

    if(networkId>-1){

           boolean status = wifi.enableNetwork(networkId_, true);

    }

对于Marshmallow:现在您的应用程序只能更改由您创建的WifiConfiguration对象的状态。您不允许修改或删除用户或其他应用程序创建的WifiConfiguration对象。 有关Marshmallow的更多信息


1
嗨,那一行代码解决了我的问题:wificonfiguration.allowedKeyManagement.set(KeyMgmt.WPA_PSK);现在连接正常工作。谢谢。 - chimaira
@xanexpt:你有没有成功地让它在安卓6上运行? - user2489122

2
自Android Lollipop和Marshmallow以来,连接WiFi网络的方式发生了一些变化。有一篇很好的博客文章与如何在Marshmallow及以下版本中连接WiFi网络相关。该文章描述了当WiFi网络没有连接和您想通过该网络发送流量(类似于强制门户)时的情况,但它也解释了完整的过程,并适用于普通网络。您不会找到完全相同的代码,但它仍可能有助于了解您卡住的地方。文章链接:http://www.intentfilter.com/2016/08/programatically-connecting-to-wifi.html

2

你需要调用 WiFiManager 的 disconnect() 和 reconnect() 方法。以下是代码示例:

                WifiConfiguration conf = new WifiConfiguration();
                conf.hiddenSSID = true;
                conf.priority = 1000;
                conf.SSID = "\"" + SSID + "\"";
                conf.preSharedKey = "\""+Password+"\"";
                conf.status = WifiConfiguration.Status.ENABLED;
                conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);

                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);

                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);

                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

                conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                int res = wifiManager.addNetwork(conf);
                boolean es = wifiManager.saveConfiguration();
                Log.d(TAG, "saveConfiguration returned " + es );
                wifiManager.disconnect();
                boolean bRet = wifiManager.enableNetwork(res, true);
                Log.i(TAG, "enableNetwork bRet = " + bRet);
                wifiManager.reconnect();

但是我们怎么知道它是否连接成功了,或者是否出现了密码错误? - NehaK
它仍然总是连接到任何先前最接近的网络,无论您添加/选择哪个新的SSID。编辑:使用@Nishkarsh的优先级方法解决了这个问题。 - behelit

0

这对于我来说适用于WPA连接。 如果已经保存了网络,则不需要再次添加。

private void connectToWifi(final String networkSSID, final String networkPassword) {
    int netID = -1;
    String confSSID = String.format("\"%s\"", networkSSID);
    String confPassword = String.format("\"%s\"", networkPassword);

    netID = getExistingNetworkID(confSSID, netID);
    /*
     * If ssid not found in preconfigured list it will return -1
     * then add new wifi
     */
    if (netID == -1) {

        Log.d(TAG,"New wifi config added");

        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = confSSID;
        conf.preSharedKey = confPassword;
        netID = wifiManager.addNetwork(conf);

    }
    wifiManager.disconnect();
    wifiManager.enableNetwork(netID, true);
    wifiManager.reconnect();
}

private int getExistingNetworkID (String confSSID, int netID){
    List<WifiConfiguration> wifiConfigurationList = wifiManager.getConfiguredNetworks();
    for (WifiConfiguration item : wifiConfigurationList){
        /*
          Find if the SSID is in the preconfigured list - if found get netID
         */
        if (item.SSID != null && item.SSID.equals(confSSID)){

            Log.d(TAG, "Pre-configured running");
            netID = item.networkId;
            break;
        }
    }
    return netID;
}

0

这是连接WiFi的正确方式,非常简短,没有样板代码。

 fun connectToWifi(ssid: String, password: String) {
    val connManager = context!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
    val wifiConfiguration = WifiConfiguration()
    wifiConfiguration.SSID = String.format("\"%s\"", ssid)
    wifiConfiguration.preSharedKey = String.format("\"%s\"", password)
    wifiManager = context!!.getSystemService(Context.WIFI_SERVICE) as WifiManager
    val netId: Int = wifiManager.addNetwork(wifiConfiguration)
    wifiManager.disconnect()
    wifiManager.enableNetwork(netId, true)
    wifiManager.reconnect()
    val config = WifiConfiguration()
    config.SSID == "\"\"" + ssid + "\"\""
    config.preSharedKey == "\"\"" + password + "\"\""
    wifiManager.addNetwork(config)
}

-1

试试这个,享受它:

 int res = mWifiManager.addNetwork(wifiConfiguration);
                                        if (res == -1) {
                            // Get existed network id if it is already added to WiFi network
                            res = getExistingNetworkId(wifiConfiguration.SSID);
                            Log.d(TAG, "getExistingNetwrkId: " + res);
                        }

      private int getExistingNetworkId(String SSID) {
            List<WifiConfiguration> configuredNetworks = mWifiManager.getConfiguredNetworks();
            if (configuredNetworks != null) {
                for (WifiConfiguration existingConfig : configuredNetworks) {
                    if (SSID.equalsIgnoreCase(existingConfig.SSID)) {
                        return existingConfig.networkId;
                    }
                }
            }
            return -1;
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接