58

What would the code be for checking whether the Wi-Fi is enabled or not?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
inforg
  • 749
  • 2
  • 8
  • 15

4 Answers4

119
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
  // wifi is enabled
}

For details check here

Jared Burrows
  • 52,770
  • 23
  • 148
  • 184
Rasel
  • 16,321
  • 6
  • 41
  • 51
25

The above answers work fine. But don't forget to add the right permissions in the Manifest:

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

Hope it helps ..

McLan
  • 2,343
  • 7
  • 44
  • 79
17

The top answer is correct, but not up to date because this code may leak memory on certain devices.

Therefore the better answer would be:

WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
  // wifi is enabled
}

Permissions in app=>mainfests=>AndroidManifest.xml:

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

Reference: https://www.mysysadmintips.com/other/programming/759-the-wifi-service-must-be-looked-up-on-the-application-context

Jared Burrows
  • 52,770
  • 23
  • 148
  • 184
KoKlA
  • 749
  • 2
  • 8
  • 15
8
public static boolean wifiState() {
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    return wifiManager.isWifiEnabled();
}
Jared Burrows
  • 52,770
  • 23
  • 148
  • 184
XXX
  • 8,870
  • 7
  • 43
  • 53