Connect android device to wifi programmatically

4.3k Views Asked by At

I need to connect my tablet to a wifi programmaticaly. I have tried a least 20 differents codes, nothing works.

I have all the permissions :

<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">

And here is the code :

  WifiConfiguration wifiConfig = new WifiConfiguration();
    wifiConfig.SSID = String.format("\"%s\"", "ssis");
    wifiConfig.preSharedKey = String.format("\"%s\"", "password");


    wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);

    WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(WIFI_SERVICE);

    int netId = wifiManager.addNetwork(wifiConfig);
    wifiManager.disconnect();
    wifiManager.enableNetwork(netId, true);
    wifiManager.reconnect();

The wifi protocol I use is WPA/WPA2

Does soemone has a working code?

1

There are 1 best solutions below

0
On

Try this code this will work on all device except android 10. Check this https://issuetracker.google.com/issues/128554616

WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", networkSSID);
wifiConfig.preSharedKey = String.format("\"%s\"", networkPass);
wifiManager = (WifiManager)                         
getActivity().getApplicationContext().getSystemService(WIFI_SERVICE);
if(!wifiManager.isWifiEnabled())
wifiManager.setWifiEnabled(true);
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();