How to Connect/Disconnect wi-fi on Android?

Asked

Viewed 819 times

3

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

1 answer

4


You can use the class WifiManager 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 the Wifi when leaving the app if it was already on when the app opened. In other words: only hang up if you called yourself.

  • Thanks, it worked here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.