How to Turn Wi-Fi on / off on Android?

3

How do I turn on and off Wifi on Android? I would like to turn the signal on every time the person opens the application, and turn it off the moment they close.

    
asked by anonymous 05.03.2014 / 03:10

1 answer

4

You can use the WifiManager class for this, in particular the function setWifiEnabled . Example (within an activity):

WifiManager wifi = (WifiManager)this.getSystemService(Context.WIFI_SERVICE)
wifi.setWifiEnabled(true); // Liga o WiFi
if (wifi.isWifiEnabled()) {
    // WiFi está ligado
}

Note that you will need to add some permissions:

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

In your particular case, I suggest not turning off WiFi when exiting the app if it was already turned on when the app was opened. In other words, just turn it off if you called yourself.

    
05.03.2014 / 03:50