The network state is always correct for Android. How?
I am trying to check the network status in an android app.
And I have code like this:
public boolean isNetworkAvailable()
{
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected())
return true;
return false;
}
This code returns true
when the network is available as expected, but it also saves true
even if the network is unavailable.
Just return true
for both cases!
Where am I making a mistake in the code?
Please note that I am running the application in my emulator.
Thanks in advance.
0
source to share
1 answer
Try below method which works amazing for me. Hope it helps you too.
public static boolean IsNetConnected()
{
boolean NetConnected = false;
try
{
ConnectivityManager connectivity =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null)
{
NetConnected = false;
}
else
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
{
for (int i = 0; i < info.length; i++)
{
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
NetConnected = true;
}
}
}
}
}
catch (Exception e)
{
NetConnected = false;
}
return NetConnected;
}
0
source to share