How do I see if Wi-Fi is connected on Android?

AndroidAndroid WifiWifimanager

Android Problem Overview


I don't want my user to even try downloading something unless they have Wi-Fi connected. However, I can only seem to be able to tell if Wi-Fi is enabled, but they could still have a 3G connection.

android.net.wifi.WifiManager m = (WifiManager) getSystemService(WIFI_SERVICE);
android.net.wifi.SupplicantState s = m.getConnectionInfo().getSupplicantState();
NetworkInfo.DetailedState state = WifiInfo.getDetailedStateOf(s);
if (state != NetworkInfo.DetailedState.CONNECTED) {
    return false;
}

However, the state is not what I would expect. Even though Wi-Fi is connected, I am getting OBTAINING_IPADDR as the state.

Android Solutions


Solution 1 - Android

You should be able to use the ConnectivityManager to get the state of the Wi-Fi adapter. From there you can check if it is connected or even available.

ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
    // Do whatever
}

NOTE: It should be noted (for us n00bies here) that you need to add

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

to your

AndroidManifest.xml for this to work.

NOTE2: public NetworkInfo getNetworkInfo (int networkType) is now deprecated:

> This method was deprecated in API level 23. This method does not > support multiple connected networks of the same type. Use > getAllNetworks() and getNetworkInfo(android.net.Network) instead.

NOTE3: public static final int TYPE_WIFI is now deprecated:

> This constant was deprecated in API level 28. Applications should instead use NetworkCapabilities.hasTransport(int) or requestNetwork(NetworkRequest, NetworkCallback) to request an appropriate network. for supported transports.

Solution 2 - Android

Since the method NetworkInfo.isConnected() is now deprecated in API-23, here is a method which detects if the Wi-Fi adapter is on and also connected to an access point using WifiManager instead:

private boolean checkWifiOnAndConnected() {
    WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    if (wifiMgr.isWifiEnabled()) { // Wi-Fi adapter is ON

        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();

        if( wifiInfo.getNetworkId() == -1 ){
            return false; // Not connected to an access point
        }
        return true; // Connected to an access point
    }
    else {
        return false; // Wi-Fi adapter is OFF
    }
}

Solution 3 - Android

I simply use the following:

SupplicantState supState; 
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
supState = wifiInfo.getSupplicantState();

Which will return one of these states at the time you call getSupplicantState();

> ASSOCIATED - Association completed. > > ASSOCIATING - Trying to associate with > an access point. > > COMPLETED - All authentication > completed. > > DISCONNECTED - This state indicates > that client is not associated, but is > likely to start looking for an access > point. > > DORMANT - An Android-added state that > is reported when a client issues an > explicit DISCONNECT command. > > FOUR_WAY_HANDSHAKE - WPA 4-Way Key > Handshake in progress. > > GROUP_HANDSHAKE - WPA Group Key > Handshake in progress. > > INACTIVE - Inactive state. > > INVALID - A pseudo-state that should > normally never be seen. > > SCANNING - Scanning for a network. > > UNINITIALIZED - No connection.

Solution 4 - Android

I am using this in my apps to check if the active network is Wi-Fi:

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI)
{

    // Do your work here

}

Solution 5 - Android

I had a look at a few questions like this and came up with this:

ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

if (wifi.isConnected()){
    // If Wi-Fi connected
}

if (mobile.isConnected()) {
    // If Internet connected
}

I use if for my license check in Root Toolbox PRO, and it seems to work great.

Solution 6 - Android

While Jason's answer is correct, nowadays getNetWorkInfo (int) is a deprecated method. So, the next function would be a nice alternative:

public static boolean isWifiAvailable (Context context)
{
    boolean br = false;
    ConnectivityManager cm = null;
    NetworkInfo ni = null;

    cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    ni = cm.getActiveNetworkInfo();
    br = ((null != ni) && (ni.isConnected()) && (ni.getType() == ConnectivityManager.TYPE_WIFI));

    return br;
}

Solution 7 - Android

The NetworkInfo class is deprecated as of API level 29, along with the related access methods like ConnectivityManager#getNetworkInfo() and ConnectivityManager#getActiveNetworkInfo().

The documentation now suggests people to use the ConnectivityManager.NetworkCallback API for asynchronized callback monitoring, or use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties for synchronized access of network information

> Callers should instead use the ConnectivityManager.NetworkCallback API to learn about connectivity changes, or switch to use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties to get information synchronously.


To check if WiFi is connected, here's the code that I use:

Kotlin:

val connMgr = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
connMgr?: return false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    val network: Network = connMgr.activeNetwork ?: return false
    val capabilities = connMgr.getNetworkCapabilities(network)
    return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
} else {
    val networkInfo = connMgr.activeNetworkInfo ?: return false
    return networkInfo.isConnected && networkInfo.type == ConnectivityManager.TYPE_WIFI
}

Java:

ConnectivityManager connMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connMgr == null) {
    return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    Network network = connMgr.getActiveNetwork();
    if (network == null) return false;
    NetworkCapabilities capabilities = connMgr.getNetworkCapabilities(network);
    return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
} else {
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    return networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}

Remember to also add permission ACCESS_NETWORK_STATE to your Manifest file.

Solution 8 - Android

Many of answers use deprecated code, or code available on higer API versions. Now I use something like this

ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if(connectivityManager != null) {
            for (Network net : connectivityManager.getAllNetworks()) {
                NetworkCapabilities nc = connectivityManager.getNetworkCapabilities(net);
                if (nc != null && nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
                        && nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET))
                    return true;
            }
        }
        return false;

Solution 9 - Android

The following code (in Kotlin) works from API 21 until at least current API version (API 29). The function getWifiState() returns one of 3 possible values for the WiFi network state: Disable, EnabledNotConnected and Connected that were defined in an enum class. This allows to take more granular decisions like informing the user to enable WiFi or, if already enabled, to connect to one of the available networks. But if all that is needed is a boolean indicating if the WiFi interface is connected to a network, then the other function isWifiConnected() will give you that. It uses the previous one and compares the result to Connected.

It's inspired in some of the previous answers but trying to solve the problems introduced by the evolution of Android API's or the slowly increasing availability of IP V6. The trick was to use:

wifiManager.connectionInfo.bssid != null 

instead of:

  1. getIpAddress() == 0 that is only valid for IP V4 or
  2. getNetworkId() == -1 that now requires another special permission (Location)

According to the documentation: https://developer.android.com/reference/kotlin/android/net/wifi/WifiInfo.html#getbssid it will return null if not connected to a network. And even if we do not have permission to get the real value, it will still return something other than null if we are connected.

Also have the following in mind:

> On releases before android.os.Build.VERSION_CODES#N, this object > should only be obtained from an Context#getApplicationContext(), and > not from any other derived context to avoid memory leaks within the > calling process.

In the Manifest, do not forget to add:

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

Proposed code is:

class MyViewModel(application: Application) : AndroidViewModel(application) {

   // Get application context
    private val myAppContext: Context = getApplication<Application>().applicationContext

   // Define the different possible states for the WiFi Connection
    internal enum class WifiState {
        Disabled,               // WiFi is not enabled
        EnabledNotConnected,    // WiFi is enabled but we are not connected to any WiFi network
        Connected,              // Connected to a WiFi network
    }
    
    // Get the current state of the WiFi network
    private fun getWifiState() : WifiState {
    
        val wifiManager : WifiManager = myAppContext.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
    
        return if (wifiManager.isWifiEnabled) {
                    if (wifiManager.connectionInfo.bssid != null)
                        WifiState.Connected
                    else
                        WifiState.EnabledNotConnected
               } else {
                    WifiState.Disabled
               }
    }
    
    // Returns true if we are connected to a WiFi network
    private fun isWiFiConnected() : Boolean {
        return (getWifiState() == WifiState.Connected)
    }
}

Solution 10 - Android

ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
boolean is3g = manager.getNetworkInfo(
                  ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
boolean isWifi = manager.getNetworkInfo(
                    ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();

Log.v("", is3g + " ConnectivityManager Test " + isWifi);
if (!is3g && !isWifi) {
    Toast.makeText(
        getApplicationContext(),
        "Please make sure, your network connection is ON ",
        Toast.LENGTH_LONG).show();
}
else {
    // Put your function() to go further;
}

Solution 11 - Android

Using WifiManager you can do:

WifiManager wifi = (WifiManager) getSystemService (Context.WIFI_SERVICE);
if (wifi.getConnectionInfo().getNetworkId() != -1) {/* connected */}

The method getNeworkId returns -1 only when it's not connected to a network;

Solution 12 - Android

Try out this method.

public boolean isInternetConnected() {
	ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	boolean ret = true;
	if (conMgr != null) {
		NetworkInfo i = conMgr.getActiveNetworkInfo();

		if (i != null) {
			if (!i.isConnected()) {
				ret = false;
			}

			if (!i.isAvailable()) {
				ret = false;
			}
		}

		if (i == null)
			ret = false;
	} else
		ret = false;
	return ret;
}

This method will help to find internet connection available or not.

Solution 13 - Android

This works for me:

    ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    // Mobile
    State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();

    // Wi-Fi
    State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();

    // And then use it like this:

    if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
    {
        Toast.makeText(Wifi_Gprs.this,"Mobile is Enabled :) ....",Toast.LENGTH_LONG).show();
    }
    else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
    {
        Toast.makeText(Wifi_Gprs.this,"Wifi is Enabled  :) ....",Toast.LENGTH_LONG).show();
    }
    else
    {
        Toast.makeText(Wifi_Gprs.this,"No Wifi or Gprs Enabled :( ....",Toast.LENGTH_LONG).show();
    }

And add this permission:

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

Solution 14 - Android

Similar to @Jason Knight answer, but in Kotlin way:

val connManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)

if (mWifi.isConnected) {
     // Do whatever
}

Solution 15 - Android

This works for Android devices before and after Q

fun isWifiConnected(context: Context):Boolean {
    val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
             val capabilities = cm.getNetworkCapabilities(cm.activeNetwork)
             capabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)==true
        } else {
            val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
            activeNetwork?.typeName?.contains("wifi",ignoreCase = true)?:false
        }
}

Solution 16 - Android

Here is what I use as a utility method in my apps:

public static boolean isDeviceOnWifi(final Context context) {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifi != null && mWifi.isConnectedOrConnecting();
}

Solution 17 - Android

In new version Android

private void getWifiInfo(Context context) {
    ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    Network[] networks = connManager.getAllNetworks();

    if(networks == null || networks.length == 0)
        return;

    for( int i = 0; i < networks.length; i++) {
        Network ntk = networks[i];
        NetworkInfo ntkInfo = connManager.getNetworkInfo(ntk);
        if (ntkInfo.getType() == ConnectivityManager.TYPE_WIFI && ntkInfo.isConnected() ) {
            final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
            if (connectionInfo != null) {
                // add some code here
            }
        }

    }
}

and add premission too

Solution 18 - Android

This is an easier solution. See Stack Overflow question https://stackoverflow.com/questions/6593858/checking-wifi-enabled-or-not-in-android.

P.S. Do not forget to add the code to the manifest.xml file to allow permission. As shown below.

<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>

Solution 19 - Android

Try

wifiManager.getConnectionInfo().getIpAddress()

This returns 0 until the device has a usable connection (on my machine, a Samsung SM-T280, Android 5.1.1).

Solution 20 - Android

You can turn WIFI on if it's not activated as the following

  1. check WIFI state as answered by @Jason Knight

  2. if not activated, activate it don't forget to add WIFI permission in the manifest file

Your Java class should be like that

public class TestApp extends Activity {
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //check WIFI activation
    ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (mWifi.isConnected() == false) {
        showWIFIDisabledAlertToUser();
    }
    else {
        Toast.makeText(this, "WIFI is Enabled in your devide", Toast.LENGTH_SHORT).show();
    }
}


private void showWIFIDisabledAlertToUser(){
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setMessage("WIFI is disabled in your device. Would you like to enable it?")
            .setCancelable(false)
            .setPositiveButton("Goto Settings Page To Enable WIFI",
                    new DialogInterface.OnClickListener(){
                        public void onClick(DialogInterface dialog, int id){
                            Intent callGPSSettingIntent = new Intent(
                                    Settings.ACTION_WIFI_SETTINGS);
                            startActivity(callGPSSettingIntent);
                        }
                    });
    alertDialogBuilder.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int id){
                    dialog.cancel();
                }
            });
    AlertDialog alert = alertDialogBuilder.create();
    alert.show();
}

}

Solution 21 - Android

Add this for JAVA:

public boolean CheckWifiConnection() {
        ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
        if (conMgr.getActiveNetworkInfo() != null
                && conMgr.getActiveNetworkInfo().isAvailable()
                && conMgr.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            return false;
        }
    }

in Manifest file add the following permissions:

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

Solution 22 - Android

Kind of old a question but this is what i use. requires min api level 21 also takes in consideration deprecated Networkinfo apis.

boolean isWifiConn = false;
    ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Network network = connMgr.getActiveNetwork();
        if (network == null) return false;
        NetworkCapabilities capabilities = connMgr.getNetworkCapabilities(network);
        if(capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
            isWifiConn = true;
            Toast.makeText(context,"Wifi connected Api >= "+Build.VERSION_CODES.M,Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(context,"Wifi not connected Api >= "+Build.VERSION_CODES.M,Toast.LENGTH_LONG).show();
        }
    } else {
        for (Network network : connMgr.getAllNetworks()) {
            NetworkInfo networkInfo = connMgr.getNetworkInfo(network);
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) {
                isWifiConn = true;
                Toast.makeText(context,"Wifi connected ",Toast.LENGTH_LONG).show();
                break;
            }else{
                Toast.makeText(context,"Wifi not connected ",Toast.LENGTH_LONG).show();
            }
        }
    }
    return isWifiConn;

Solution 23 - Android

val wifi = context!!.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?        
         if (wifi!!.isWifiEnabled) 
              //do action here
    
         else 
             //do action here
    
        
                    

Solution 24 - Android

This works with the latest versions of android:

fun getConnectionType(context: Context): ConnectivityType {
    var result = NONE
    val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (cm != null) {
            val capabilities = cm.getNetworkCapabilities(cm.activeNetwork)
            if (capabilities != null) {
                when {
                    capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
                        result = WIFI
                    }
                    capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
                        result = MOBILE_DATA
                    }
                    capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> {
                        result = VPN
                    }
                }
            }
        }
    } else {
        if (cm != null) {
            val activeNetwork = cm.activeNetworkInfo
            if (activeNetwork != null) {
                // connected to the internet
                when (activeNetwork.type) {
                    ConnectivityManager.TYPE_WIFI -> {
                        result = WIFI
                    }
                    ConnectivityManager.TYPE_MOBILE -> {
                        result = MOBILE_DATA
                    }
                    ConnectivityManager.TYPE_VPN -> {
                        result = VPN
                    }
                }
            }
        }
    }
    return result
}

enum class ConnectivityType {
    NONE,
    MOBILE_DATA,
    WIFI,
    VPN,
}

And in the manifest:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNathan SchwermannView Question on Stackoverflow
Solution 1 - AndroidJason KnightView Answer on Stackoverflow
Solution 2 - AndroidrevolutionaryView Answer on Stackoverflow
Solution 3 - AndroidDonal RaffertyView Answer on Stackoverflow
Solution 4 - AndroidkuchiView Answer on Stackoverflow
Solution 5 - AndroidLukeMovementView Answer on Stackoverflow
Solution 6 - AndroidVal MartinezView Answer on Stackoverflow
Solution 7 - AndroidJackView Answer on Stackoverflow
Solution 8 - AndroidOleg ShevchenkoView Answer on Stackoverflow
Solution 9 - AndroidDarkJediNinjaView Answer on Stackoverflow
Solution 10 - AndroidG M RameshView Answer on Stackoverflow
Solution 11 - AndroidrazzView Answer on Stackoverflow
Solution 12 - AndroidM DView Answer on Stackoverflow
Solution 13 - AndroidAhmadView Answer on Stackoverflow
Solution 14 - AndroidJerry ChongView Answer on Stackoverflow
Solution 15 - AndroidNasser GhodsianView Answer on Stackoverflow
Solution 16 - AndroidMahendra LiyaView Answer on Stackoverflow
Solution 17 - AndroidAlbert NguyenView Answer on Stackoverflow
Solution 18 - AndroidClaydenView Answer on Stackoverflow
Solution 19 - AndroidAdrianView Answer on Stackoverflow
Solution 20 - AndroidAhmed BelalView Answer on Stackoverflow
Solution 21 - AndroidSagittariusView Answer on Stackoverflow
Solution 22 - AndroidkatwekibsView Answer on Stackoverflow
Solution 23 - AndroidHandyPawanView Answer on Stackoverflow
Solution 24 - AndroidBollingView Answer on Stackoverflow