We often use below code to check internet...
/**
* Checks if the device has Internet connection.
* @return <code>true</code> if the phone is connected to the Internet.
*/
public static boolean hasConnection() {
ConnectivityManager cm = (ConnectivityManager) MbridgeApp.getContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
return true;
}
NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNetwork != null && mobileNetwork.isConnected()) {
return true;
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
}
return false;
}
Or something like this...
/**
* Method is using Connectivity Services to get Connectivity manager. that will find network informations
* If we found connected state of any network that means we are connected to a network
* @return true if we are connected otherwise false
*/
public Boolean isConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager != null) {
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if(info != null) {
for (NetworkInfo i : info) {
if (i.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
Ok, Now the problem is, these both methods will return true even we don't have sufficient mobile/cellular data (Internet Balance) or zero balance. That is not a good condition to perform any task related to the internet like calling an API etc. So question is that how to precise these methods? Can I check data balance programmatically?