Android: How to Enable/Disable Wifi or Internet Connection Programmatically Android: How to Enable/Disable Wifi or Internet Connection Programmatically android android

Android: How to Enable/Disable Wifi or Internet Connection Programmatically


I know of enabling or disabling wifi:

WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);wifiManager.setWifiEnabled(status);

where status may be true or false as per requirement.

Edit:

You also need the following permissions in your manifest file:

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


To Enable WiFi:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);wifi.setWifiEnabled(true);

To Disable WiFi:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);wifi.setWifiEnabled(false);

Note:To access with WiFi state, we have to add following permissions inside the AndroidManifest.xml file:

android.permission.ACCESS_WIFI_STATEandroid.permission.UPDATE_DEVICE_STATS android.permission.CHANGE_WIFI_STATE


A complete solution:

try {    WifiManager wifi = (WifiManager)         context.getSystemService(Context.WIFI_SERVICE);    WifiConfiguration wc = new WifiConfiguration();    wc.SSID = "\"SSIDName\"";    wc.preSharedKey  = "\"password\"";    wc.hiddenSSID = true;    wc.status = WifiConfiguration.Status.ENABLED;     wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);    wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);    wc.allowedPairwiseCiphers        .set(WifiConfiguration.PairwiseCipher.TKIP);    wc.allowedPairwiseCiphers        .set(WifiConfiguration.PairwiseCipher.CCMP);    wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);    boolean b=wifi.isWifiEnabled();    if (b) {        wifi.setWifiEnabled(false);        Toast.makeText(context, "yes", Toast.LENGTH_SHORT).show();    } else {        wifi.setWifiEnabled(true);        Toast.makeText(context, "no", Toast.LENGTH_SHORT).show();    }    //Log.d("WifiPreference", "enableNetwork returned " + b );} catch (Exception e) {    e.printStackTrace();}

Reference: http://amitkumar-android.blogspot.com/p/installation-steps.html