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

时间:2016-02-21 17:17:36

标签: android wifi android-6.0-marshmallow wifimanager

我正在尝试通过提供SSID并使用WifiManager配置传递来连接到wifi网络。

基于此线程解决方案: How do I connect to a specific Wi-Fi network in Android programmatically?

调用重新连接方法。但没有任何事情发生(没有连接)。

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

7 个答案:

答案 0 :(得分:11)

自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" />

答案 1 :(得分: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);

    }

对于棉花糖:您的应用程序现在只有在您创建这些对象时才能更改WifiConfiguration对象的状态。您不得修改或删除用户或其他应用程序创建的WifiConfiguration对象。 More info on Marshmallow

答案 2 :(得分: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();

答案 3 :(得分:1)

自Android Lollipop和Marshmallow以来,您如何连接到WiFi网络已经发生了一些变化。有关于如何连接到Marshmallow及以下版本的WiFi网络的好文章

http://www.intentfilter.com/2016/08/programatically-connecting-to-wifi.html

该帖子描述了WiFi网络没有连接并且您希望通过该网络发送流量的情况(类似于强制网络门户)。但它也解释了整个过程,并适用于普通网络。你不会找到确切的代码,但它可能仍然有助于你知道你被困在哪里。

答案 4 :(得分: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;
}

答案 5 :(得分: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)
}

答案 6 :(得分:-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;
        }