开发者

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

开发者 https://www.devze.com 2023-01-18 21:38 出处:网络
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.

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.


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.


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


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.


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

}


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.


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.


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


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;


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


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;


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


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


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.


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


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
}


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


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


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>


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


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

}


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


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;


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号