Checking Wi-Fi enabled or not on Android

2019-02-03 21:31发布

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

4条回答
Ridiculous、
2楼-- · 2019-02-03 22:05
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled()){
//wifi is enabled
}

For details check here

查看更多
仙女界的扛把子
3楼-- · 2019-02-03 22:07

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 wifi =(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifi.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

查看更多
Lonely孤独者°
4楼-- · 2019-02-03 22:18

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>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
</uses-permission>

Hope it helps ..

查看更多
ら.Afraid
5楼-- · 2019-02-03 22:22
public static boolean wifiState()
{
    WifiManager mng = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    return mng.isWifiEnabled();
}
查看更多
登录 后发表回答