Maximilian Horn
Maximilian Horn

Reputation: 43

Unable to Connect to Wifi via Application

I have given data from my runtime

 ssid = "Some SSID";
 password = "myPassword";

and I want to use them to connect to a WIFI. My Code so far:

try {
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\"";

        conf.preSharedKey = "\"" + password + "\"";

        conf.status = WifiConfiguration.Status.ENABLED;
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

        WifiManager wifiManager = (WifiManager) MainActivity.this.getSystemService(Context.WIFI_SERVICE);
        int netId = wifiManager.addNetwork(conf);
        wifiManager.enableNetwork(netId, true);
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }
// ignore the returns

The problem is, my addNetork() returns -1 and thus my enableNetowrk() fails. I am open to any suggestions or even refactor. I also know that it will be WPA for all cases so there is no differ needed...

Upvotes: 0

Views: 272

Answers (1)

Tanmay Ranjan
Tanmay Ranjan

Reputation: 324

Try this snippet of code to connect Wi-Fi upto Sdk 28

 WifiManager wifiManager = (WifiManager) mContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null) {
           if (!wifiManager.isWifiEnabled()) {
                wifiManager.setWifiEnabled(true);
            }
            WifiConfiguration wifiConfig = new WifiConfiguration();
            wifiConfig.SSID = String.format("\"%s\"", deviceSsid);
            wifiConfig.preSharedKey = String.format("\"%s\"", devicePass);

            int networkId = wifiManager.getConnectionInfo().getNetworkId();
            wifiManager.removeNetwork(networkId);
            wifiManager.saveConfiguration();
            //remember id
            int netId = wifiManager.addNetwork(wifiConfig);
            wifiManager.disconnect();
            wifiManager.enableNetwork(netId, true);
            wifiManager.reconnect();
        }

If you are Connecting Wifi in Android 10 and above then there are many options like Wi-Fi suggestion API, WifiNetworkSpecifier API but I prefer Setting Panel.

For opening Setting Panel use

Intent panelIntent = new Intent(Settings.Panel.ACTION_WIFI);
startActivityForResult(panelIntent,101);

And get its callback inside onActivityResult(int requestCode, int resultCode, @Nullable Intent data).

Upvotes: 0

Related Questions