Reputation: 23
I am using the code below to check if there is a network available or not , but sometimes the network is available but there's no data transfer , this is making my internet connection fails and throw an exception .
this is the code :
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
so , who can help me finding a solution ?
Thanks
Upvotes: 0
Views: 1464
Reputation: 16739
I am using following code to check the connectivity because I think just geting the network info does not guarantee internet connectivity. Hence I think it is better to make an actual HTTP request to a remote URL and see if it is successful.
public static boolean isInternetAvailable(Context cxt) {
ConnectivityManager cm = (ConnectivityManager) cxt
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting() && canHit()) {
Log.i(App.TAG, "Network connection available.");
return true;
}
return false;
}
public static boolean canHit() {
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.connect();
urlConnection.disconnect();
return true;
} catch (Exception e){
e.printStackTrace();
return false;
}
}
Upvotes: 1
Reputation: 1992
The user may be on a BT openzone or similar connection where they have a connection but do not have internet access until they supply a password via a web browser. Data connection issues are always going to happen, you just have to handle them in each case.
Also checkout
isConnectedOrConnecting()
Which checks whether the user is still establishing a connection. See http://developer.android.com/reference/android/net/NetworkInfo.html
Upvotes: 0