Dear reader,

This site finally got its much-needed overhaul. I tried to keep existing pages at their original URLs.
Should you find an error, please do tell me at contact@aspyct.org.
Feel free to visit the new website, which may contain more documentation pertaining to your search.

Thank you for visiting aspyct.org, I hope you'll find what you're looking for.

Old Aspyct.org blog

 or  go to the new site.

Android: Switch wifi on/off

Sometime you simply need more than HTTP requests or buttons. Sometimes you need to play with device state, switch the wifi on for example. Android provide a very easy API to do that.

And to do that, we need to use the WifiManager. As any other system service, we can get it through the context, usually our activity.

Let’s write some code to toggle the wifi state. It involves 1. getting the current state and 2. changing it to the other state. But first things first, we need the permissions.

1
2
3
<!--  Add these permissions to your android manifest -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

And now that we have the permissions, finally, the code!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void toggleWifi() {
  // Get the WifiManager service from the context
  WifiManager wm = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

  // Read the current state. True is On, False is Off
  boolean currentState = wm.isWifiEnabled();

  // And now, switch to the other state
  wm.setWifiEnabled(!currentState);

  // You're done :)
  // Note that it can take some time for the wifi to reconnect
  // when you switch it on.
}