Friday, May 6, 2011

Turn off, Turn on wifi in android via code

Here is how to turn on and turn off wifi in android.

First you need to declare the following in your manifest file:

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

Now in your activity, do this to control WiFi:

private WifiManager wifiManager;
public void onCreate(Bundle icicle) {
  -- your usual stuff -- 

  // Get the Wifi service from our system
  wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

  // Check the our wifi is currently turned on or turned off

Complete reference to the WiFi code in android