0

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...

Gugu72
  • 2,052
  • 13
  • 35

1 Answers1

0

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).

Tanmay Ranjan
  • 318
  • 2
  • 8
  • I already tried the above code. the lower one i have tried all the api´s without success. Also i dont need the settings panel because it shows all avaiable networks without passwords. I already know which network i want to connect to with which password – Maximilian Horn Jan 14 '21 at 14:50