Android 6 : Connect to specific wifi network programmatically not working
Asked Answered
E

7

5

I am trying to connect to a wifi network by giving the SSID and pass using WifiManager configurations.

Based on this threads solution: How do I connect to a specific Wi-Fi network in Android programmatically?

The reconnect method is called. but nothing happens (not connected).

Is the Android version (6.0.1) for something? If yes then how to perform a network connection programmatically on Android 6?

Escallop answered 21/2, 2016 at 17:17 Comment(1)
Did you get solution?Carrelli
F
12

A few things have change to connect to a WiFi network in android Marshmallow. The following code will help you...If you are using Android 6.0 or lowlevel versions...

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;
}

And add permissions in the Manifest file

<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" />
Flank answered 12/6, 2017 at 9:27 Comment(0)
E
3

Add a wifi configuration using addNetwork and then connect to it using 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);

    }

For marshmallow: Your apps can now change the state of WifiConfiguration objects only if you created these objects. You are not permitted to modify or delete WifiConfiguration objects created by the user or by other apps. More info on Marshmallow

Elizabethelizabethan answered 7/3, 2016 at 14:8 Comment(2)
HI, that line solved my problem : wificonfiguration.allowedKeyManagement.set(KeyMgmt.WPA_PSK); Now the connection is working. ThanksEscallop
@xanexpt: Did you get it working for android 6 by any chance?Hydatid
I
2

A few things have changed about how you connect to a WiFi network since android Lollipop and Marshmallow. There is a nice blog post related to how you connect to WiFi network on Marshmallow and below versions

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

The post describes a scenario when WiFi network has no connectivity and you want to send traffic through that network (something like captive portal). But it also explains the complete process and would work for normal networks. You won't find the exact code but it might still help in knowing where you got stuck.

Ignaz answered 24/8, 2016 at 12:56 Comment(0)
C
2

You need to call disconnect() and reconnect() of WiFiManager. This works for me:

                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();
Contrariety answered 23/2, 2017 at 19:18 Comment(2)
but how we will find that its connecting, or got any password error?Tousle
It still always connects to any previous closest network, not matter which new SSID you add / select. EDIT: Using @Nishkarsh's priority method resolves this problemValdemar
F
0

This works for me for a WPA connection. You don't need to add again a network if it is already saved.

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;
}
Firebrick answered 1/7, 2018 at 17:32 Comment(0)
T
0

This is correct way to connect the wifi and this very short no boilerplate code

 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)
}
Timbuktu answered 6/8, 2019 at 15:53 Comment(0)
A
-1

Try this and enjoy:

 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;
        }
Arsenical answered 29/4, 2017 at 14:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.