Android: How to launch WiFi through code

nilA picture nilA · Apr 20, 2012 · Viewed 8.2k times · Source

i want to make an simple app which detect the wifi networks and after selecting a network it launch(connect) to the selected network.

i have written code for detection phase but how could i connect to the selected network in onItemClick(). Please suggest the code.

Answer

Priebe picture Priebe · Apr 20, 2012

You can do this by using the WifiManager. Get the Wifi Service from the system, check if the wifi is turn on or off, then turn it on/off.

private WifiManager wifiManager;
@Override
public void onCreate(Bundle bund) {
  wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
  if(wifiManager.isWifiEnabled()){
    wifiManager.setWifiEnabled(false);
  }else{
    wifiManager.setWifiEnabled(true);
  }
}

Remember do add the permissions also

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