riadrifai
riadrifai

Reputation: 1158

Proper way to check if Wifi is connected in android

For my app, I need to make sure the user is connected to wifi before contact with the server. I have found two methods to do so, but I am not sure if one suffices.

First I am adding this:

WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext()
            .getSystemService(WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
        buildAlertNoWifi();
        showProgressDialog(false, "");
        return;
}

And then I am doing this:

ConnectivityManager cm = (ConnectivityManager) getActivity()
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null) { // connected to the internet
        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
            // connected to wifi

        } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
            // connected to the mobile provider's data plan
            Toast.makeText(getContext(), "Make sure you connect to wifi.", Toast.LENGTH_LONG).show();
            return;
        }
    } else {
        Toast.makeText(getContext(), "Make sure you connect to wifi.", Toast.LENGTH_LONG).show();
        return;
    }

So I was wondering if wifiManager.isWifiEnabled() returns whether the device is connected to a wifi or just has wifi turned on. And if so, is it enough to use it alone?

Upvotes: 2

Views: 6606

Answers (3)

Farid Haq
Farid Haq

Reputation: 4199

Best Practice

public boolean isWifiConnected() {
    NetworkInfo net = getActiveNetworkInfo();
    return (isConnected(net) && net.getType() == TYPE_WIFI);
}

private NetworkInfo getActiveNetworkInfo() {
    ConnectivityManager connManager = (ConnectivityManager) 
Application.getContext()
            .getSystemService(Application.CONNECTIVITY_SERVICE);
    return connManager.getActiveNetworkInfo();
}

Upvotes: 1

lakshman.pasala
lakshman.pasala

Reputation: 565

I believe this should work,

   public boolean isWifiConnected()
    {
        ConnectivityManager cm = (ConnectivityManager)this.mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

        return (cm != null) && (cm.getActiveNetworkInfo() != null) &&
                (cm.getActiveNetworkInfo().getType() == 1);
    }

Upvotes: 0

Daniel
Daniel

Reputation: 26

I believe WifiManager.isWifiEnabled() only checks if device's wifi is turned on. Please use NetworkInfo.isConnected() or NetworkInfo.isConnectedOrConnecting() to check if it's connected to any network.

Upvotes: 1

Related Questions