245

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Nathan Schwermann
  • 30,406
  • 15
  • 78
  • 89
  • 2021 working solution: https://stackoverflow.com/questions/66573565/android-get-status-of-wifi-connection/66648761 – Sam Chen Mar 16 '21 at 03:40

23 Answers23

476

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.

Vadik
  • 296
  • 1
  • 14
Jason Knight
  • 5,764
  • 1
  • 14
  • 14
  • 72
    It should be noted (for us noobies here) that you need to add `android.permission.ACCESS_NETWORK_STATE` to your AndroidManifest.xml for this to work. – mgalgs Sep 24 '11 at 08:56
  • John x, to get it to work, use "Context.CONNECTIVITY_SERVICE". – Andy Stampor Nov 19 '13 at 18:57
  • @Jason Knight : can I identity which wifi- conntion that i connect? This is my question Can you please help me ? http://stackoverflow.com/questions/20394265/android-turn-off-mobile-network-and-access-internet-only-via-specific-wifi – Lahiruzz Dec 05 '13 at 08:01
  • 10
    In very recent versions of Android, you need to check for NULL in mWiFi ... your code here could throw a null pointer error. See http://developer.android.com/training/basics/network-ops/managing.html and in particular "The method getActiveNetworkInfo() returns a NetworkInfo..." – eb80 Jun 05 '14 at 12:24
  • Looking at the source, I can't see how you can ever me considered 'connected'- the no wifi supplicant state is mapped to a 'connected' detailed state (and therefore a connected network state). Can anyone elaborate on what's going on? – Sam Jun 01 '15 at 07:46
  • Can you check [this question](http://stackoverflow.com/questions/31689513/broadcastreceiver-to-detect-network-is-connected) – Skizo-ozᴉʞS Aug 02 '15 at 13:21
  • 1
    It worked for me with Ethernet interface as well. I just changed to **ConnectivityManager.TYPE_ETHERNET** – MBH Sep 23 '15 at 07:47
  • 3
    The method NetworkInfo.isConnected() is now depreceated in API-23. I am posting a solution below . – revolutionary Jan 20 '16 at 15:37
  • @revolutionary i dont see deprecation on sdk26 now – Jemshit Iskenderov Dec 26 '17 at 11:47
  • 2
    [NetworkInfo.getType()](https://developer.android.com/reference/android/net/NetworkInfo#getType()) and [ConnectivityManager.TYPE_WIFI](https://developer.android.com/reference/android/net/ConnectivityManager#TYPE_WIFI) are now deprecated in API 28. To avoid lint warning you should use something like `connectivityManager.getNetworkCapabilities(network).hasTransport(NetworkCapabilities.TRANSPORT_WIFI)` – Vadik Oct 09 '18 at 09:55
81

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
    }
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
revolutionary
  • 2,940
  • 3
  • 29
  • 51
  • 4
    It's worth mentioning that wifiInfo can be null so I think you should check for null before getting network id – Nonos Jul 07 '16 at 20:58
  • 2
    [`NetworkInfo.isConnected()`](https://developer.android.com/reference/android/net/NetworkInfo.html#isConnected()) doesn't look deprecated to me. – EricRobertBrewer Mar 31 '17 at 19:45
  • Don't forget to add permission: `android.permission.ACCESS_WIFI_STATE` – Ton Snoei Mar 28 '18 at 11:30
  • 1
    This will no longer work in Android Q without location permission and location mode turned on, see https://issuetracker.google.com/issues/136021574. – Konsumierer Jun 27 '19 at 08:35
  • @EricRobertBrewer comment no longer up to date. it is now, deprecated API 29+. – nuKs Mar 09 '20 at 15:00
36

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.

Armand
  • 21,079
  • 16
  • 81
  • 113
Donal Rafferty
  • 19,239
  • 37
  • 110
  • 186
  • hi Donal.I have used the same way to get whether our device is connected to wifi.But additionally i need to know the App name currently using WIFI.How can that b done? – AbhishekB Mar 28 '12 at 11:41
  • @AbhishekB, sorry but I don't have any experience with that, perhaps try looking at some of the Wi-Fi monitoring apps, see if there is an open source one where you can review the code. – Donal Rafferty Mar 28 '12 at 14:40
  • I'm suspicious of this solution because the supplicant is only used if WPA (or some variation of WPA) is usesd: if user connects to an AP with no authentication or WEP then the supplicant is not involved. – Tom May 14 '12 at 17:23
  • This is indeed true and Jason Knight's solution is better if supplicant info is not required – Donal Rafferty May 30 '12 at 15:47
  • 2
    It still shows up as "COMPLETED" even though I'm not on wifi – Evan Parsons Apr 26 '16 at 23:02
  • 1
    is there any system broadcast intent for above mentioned states ? @DonalRafferty – Rohit Singh Apr 09 '17 at 11:33
  • This will no longer work in Android Q without location permission and location mode turned on, see https://issuetracker.google.com/issues/136021574. – Konsumierer Jun 27 '19 at 08:35
20

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

}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
kuchi
  • 812
  • 10
  • 17
18

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
LukeMovement
  • 181
  • 1
  • 2
  • 8
    looks good but I'm not sure why you get a second reference to ConnectivityManager. In this example connManager and connManager1 are both the same Object – Nathan Schwermann Jul 09 '11 at 18:23
  • 1
    Does TYPE_MOBLIE means 3gnet or gprs net? – herbertD Aug 15 '12 at 06:34
  • 1
    TYPE_MOBILE means any data using your carrier - 2G (GPRS...), 3G (HSDPA...) or 4G (LTE...). – Eugen Pechanec Mar 21 '14 at 09:29
  • 1
    you may add **TYPE_ETHERNET** which worked fine when connecting android to Ethernet – MBH Sep 23 '15 at 08:09
  • 1
    It is worth bearing in mind, that `getNetworkInfo()` will return a null, if the network doesn't exist. So if the device has no mobile connection, this will throw an error. In most cases, TYPE_ETHERNET will cause a null in this case, since most devices will not have an Ethernet connection. – Knossos Dec 23 '15 at 06:36
7

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;
}
Community
  • 1
  • 1
Val Martinez
  • 543
  • 5
  • 14
6

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.

Jack
  • 3,757
  • 1
  • 21
  • 47
3
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;
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
G M Ramesh
  • 3,264
  • 9
  • 32
  • 53
  • 1
    it would be better to add some explanation rather than just code. – EdChum Oct 28 '12 at 00:15
  • 2
    I would use ***isConnected()***, the docs say: `boolean isConnectedOrConnecting ()` Indicates whether network connectivity exists or is in the process of being established. This is good for applications that need to do anything related to the network other than read or write data. For the latter, call `isConnected()` instead, which guarantees that the network is fully usable. – 18446744073709551615 Jan 21 '13 at 10:12
3

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;

razz
  • 8,452
  • 6
  • 45
  • 61
  • WIFI_STATE_DISABLED Constant Value: 1 (0x00000001) WIFI_STATE_DISABLING Constant Value: 0 (0x00000000) WIFI_STATE_ENABLED Constant Value: 3 (0x00000003) WIFI_STATE_ENABLING Constant Value: 2 (0x00000002) WIFI_STATE_UNKNOWN Constant Value: 4 (0x00000004) – Lou Morda Nov 06 '17 at 18:17
  • https://developer.android.com/reference/android/net/wifi/WifiManager.html – Lou Morda Nov 06 '17 at 18:18
  • This will no longer work in Android Q without location permission and location mode turned on, see https://issuetracker.google.com/issues/136021574. – Konsumierer Jun 27 '19 at 08:35
3

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;
Oleg Shevchenko
  • 111
  • 1
  • 4
3

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)
    }
}
DarkJediNinja
  • 325
  • 3
  • 9
2

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.

M D
  • 46,860
  • 8
  • 87
  • 108
  • 1
    I was looking specifically if the active connection is wifi. Also, no need to do a null check on conMgr it will never be null. – Nathan Schwermann Dec 06 '13 at 15:49
  • Can you check [this question](http://stackoverflow.com/questions/31689513/broadcastreceiver-to-detect-network-is-connected) please? :( – Skizo-ozᴉʞS Aug 02 '15 at 13:21
2

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" />
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Ahmad
  • 73
  • 1
  • 5
1

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();
}
Mahendra Liya
  • 11,166
  • 10
  • 79
  • 105
  • It is good to point out that isConnectedOrConnecting method is important when you are checking for establishing connection. The IsConnected method did not work for me. – vincent Aug 04 '16 at 04:33
1

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

Albert Nguyen
  • 211
  • 2
  • 6
1

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
}
Jerry Chong
  • 3,606
  • 1
  • 27
  • 29
0

This is an easier solution. See Stack Overflow question Checking Wi-Fi enabled or not on 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>
Community
  • 1
  • 1
Clayden
  • 21
  • 3
0

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

Adrian
  • 1
  • 1
0

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

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

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();
}

}

0

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" />
0

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;
katwekibs
  • 946
  • 9
  • 15
0
val wifi = context!!.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?        
         if (wifi!!.isWifiEnabled) 
              //do action here
    
         else 
             //do action here
    
        
                    
HandyPawan
  • 638
  • 1
  • 7
  • 11
0

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" />
Bolling
  • 3,297
  • 22
  • 24