Reputation: 8190
Sometimes, I have to check internet connection in my android app:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
The code above only work when one Network
available! However, my Device has wifi
and 3G
, the code above always return false
when I use both 2 type of network connection above! (I still can use google.com
when It return false
)!! What did I miss? Thanks!
Upvotes: 3
Views: 3599
Reputation: 5554
What about this code?
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
// Check the current state of the Network Information
if (networkInfo == null)
return false;
if (networkInfo.isConnected() == false)
return false;
if (networkInfo.isAvailable() == false)
return false;
return true;
Remember to add this in your application manifest file also :
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Upvotes: 2
Reputation: 21191
Try this
private boolean haveNetworkConnection()
{
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo)
{
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
Upvotes: 2