Paul Alexander Paul Alexander - 1 year ago 65
Java Question

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)
myWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

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

Answer Source

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;
        return false;


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download