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

Posted on

Question :

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.


Answer :

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.


Leave a Reply

Your email address will not be published. Required fields are marked *