58

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
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
  • 54,294
  • 25
  • 151
  • 185
Rasel
  • 15,499
  • 6
  • 40
  • 50
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,552
  • 9
  • 51
  • 85
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
  • 54,294
  • 25
  • 151
  • 185
KoKlA
  • 898
  • 2
  • 11
  • 15
8
public static boolean wifiState() {
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    return wifiManager.isWifiEnabled();
}
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
XXX
  • 8,996
  • 7
  • 44
  • 53