Search code examples
javaandroidwifiandroid-wifi

How to check that wifi is NOT connected on android


Ive written some code in an app to check if the phone has a wifi connection, I can do this fine and it works but what I actually want to check for is when the phone is not connected to wifi but it doesn't seem to be working. I think I must have the syntax wrong somewhere. please see code below:

ConnectivityManager connManager = (ConnectivityManager)
getSystemService(CONNECTIVITY_SERVICE);
myWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (!myWifi.isConnected()){
        //do something         
    }

Solution

  • With the ACCESS_NETWORK_STATE permission in your manifest

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

    Using the getActiveNetworkInfo() method, use this method:

    private boolean notConnectedToWifi(){
        final ConnectivityManager conMgr = (ConnectivityManager).getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected() && activeNetwork.getType() != ConnectivityManager.TYPE_WIFI) 
            return true;
        else
            return false;
    
    }
    

    All you have to do next is to call the method in your condition. Example

    if(notConnectedToWifi){
     // Oops! You're not connected to wifi!
    }
    

    Note that I check if activeNetwork is connected via activeNetwork.isConnected() so if the device is connected to a mobile network, the method notConnectedToWifi() will return false. It will also return false if it isn't connected to any network.