0

I want to connect to a wifi network so I try this:

WifiConfiguration wfc = new WifiConfiguration();

wfc.SSID = "\"".concat( sid ).concat("\"");
wfc.preSharedKey = "\"".concat( pwd ).concat("\"");

WifiManager wfMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
int networkId = wfMgr.addNetwork(wfc);
if (networkId != -1) {
    // success, can call wfMgr.enableNetwork(networkId, true) to connect
} else {
    // fails
}

but networkId is always -1 where is the error?

The necessary permissions are also added in the manifest:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" android:required="true"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" android:required="true"/>
mrpep
  • 131
  • 3
  • 12

2 Answers2

0

The documentation says:

Add a new network description to the set of configured networks. The networkId field of the supplied configuration object is ignored.

The new network will be marked DISABLED by default. To enable it, called enableNetwork(int, boolean). Parameters config the set of variables that describe the configuration, contained in a WifiConfiguration object.

Returns the ID of the newly created network description. This is used in other operations to specified the network to be acted upon. Returns -1 on failure.

So, my guess is that you need to do this:

wfMgr.enableNetwork(netId,true);

netId: the ID of the network in the list of configured networks.

Community
  • 1
  • 1
Carlos
  • 388
  • 2
  • 13
  • 33
  • wfMgr is a WifiManager so the method is public int addNetwork (WifiConfiguration config). There isn't int addNetwork( WifiConfiguration config, boolean xxx ) – mrpep Jan 12 '16 at 15:46
  • If I have netId = -1 I can't use wfMgr.enableNetwork(netId,true); – mrpep Jan 12 '16 at 16:06
0

You can do this

public static void addNewConnection(final String networkSSID, String networkPassword, String securityType, Context context)
    {
        // Default settings for all networks
        wifiConfig = new WifiConfiguration();
        wifiConfig.SSID = "\"".concat(networkSSID).concat("\"");
        wifiConfig.status = WifiConfiguration.Status.ENABLED;
        wifiConfig.hiddenSSID = true;
        wifiConfig.priority = 40;


        connectToNewWifiConfig(wifiConfig, context);
    }

    private static boolean connectToNewWifiConfig(final WifiConfiguration wc, Context context)
    {
        wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        boolean success = false;
        final int actNetId = wifi.getConnectionInfo().getNetworkId();
        WifiInfo wifiInfo = wifi.getConnectionInfo();
        String prevNetworkSSID = wifiInfo.getSSID();
        int netId = wifi.addNetwork(wc);
        if (netId != ApplicationConstants.INVALID_NETWORK_ID)
        {
            success = wifi.saveConfiguration();
        }
        return success;
    }
tanmeet
  • 220
  • 2
  • 11