Reputation: 2108
I am using wifi and GPRS to connect the internet.but in some situations such as wifi connected but no internet connection and same with data (GPRS).data on but no net connections.
for wifi i am using below code.this returns true always
public static boolean isConnectedWifi(Context context) {
NetworkInfo info=null;
if(context!=null){
info= IsNetConnectionAvailable.getNetworkInfo(context);
}
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}
and for mobile data i am using below code. it will give true or false based on data on off.
public boolean isMobileDataEnable() {
boolean mobileDataEnabled = false; // Assume disabled
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Class cmClass = Class.forName(cm.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true); // Make the method callable
// get the setting for "mobile data"
mobileDataEnabled = (Boolean) method.invoke(cm);
} catch (Exception e) {
// Some problem accessible private API and do whatever error handling you want here
}
return mobileDataEnabled;
}
but how to catch the condition when there is no internet connection on both condition? is there any android api can help for above situations. please help me to resolve this.
Upvotes: 2
Views: 4533
Reputation: 1356
Method to get network type either it is mobile or wifi.
public static String getNetworkType(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return info.getTypeName();
}
Method to check whether phone is connected to INTERNET or not
public static boolean isInternetIsConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
return true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
return true;
}
} else {
// not connected to the internet
return false;
}
return false;
}
You can use the below library for more control over the network connection.
Upvotes: 4
Reputation: 13
You can use this Facebook Connection Class to find the network speed and whether you are connected to the web or not. For every activity, you don't need to check just create one Application Class and implement the logic and through that class fetch the connection checker.
I have implemented this for Live Streaming, whether I have an active network connection with a specified range of bandwidth. I don't have a working code for your scenario. It might help.
Upvotes: 1