问题
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