Checking if wifi is connected returning false even though it is connected

折月煮酒 提交于 2020-01-05 08:23:25

问题


I am working on an android project and I am trying to check if an android device is connected to Wifi, however, my function is always returning false, even though my device is successfully connected to Wifi.

In the constructor for the class I pass the context of the calling method, and within the constructor I create an instance of the ConnnectivityManager

Below is the constructor

public NetworkManagement(Context context)
{
    this.context = context;
    connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
}

Below is my function that I am having the problem with

public boolean isConnectedToWifi()
{
    NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (networkInfo.isConnected())
    {
        return true;
    }
    else
    {
        return false;
    }
}

Even though my device is connected to a wifi network and I can successfully connect to the internet, the function above will always return false but I do not understand why.

Thanks for any help you can provide.


回答1:


public class NetworkManagement
{
    public Context context;

    public NetworkManagement(Context context)
    {
        this.context = context;     
    }

    public boolean isConnectedToWifi()
    {
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (networkInfo.isConnected())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

}

and call

//tested with context=getApplicationContext();
NetworkManagement a = new NetworkManagement(context);
Boolean z = a.isConnectedToWifi();

z should return it properly

Edit : It still isn't working properly then i take it. If it still isn't it would be a fault in the context



来源:https://stackoverflow.com/questions/18947906/checking-if-wifi-is-connected-returning-false-even-though-it-is-connected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!