问题
I'm trying to check the network status in my android application.
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 is returning true
when network is available as expected but it is also returing true
even in case of network not-available.
Simply put its returning true
for both the cases!
Where I'm making the mistake in the code?
Note that I run the app in my emulator.
Thanks in advance.
回答1:
Try out below method it works awesome for me. I hope it will help you also.
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; }
来源:https://stackoverflow.com/questions/14577181/network-status-is-always-true-for-android-how