You can check the availability of internet connection in android device by using the following source code example. While building android web applications it is necessary to check whether the device has internet connection available or not. This concept is very important and is very useful while developing android applications for validation purposes.
Android Source Code Example to Check Internet Connectivity
1. The below main activity returns the boolean value as true if there is internet connection in the device and if it returns false then there is no internet access in the android device.
public class isNetworkAvailable {
//return boolean as true if there is internet access
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
2. Please add the USES permission (Internet / Wifi) in the android manifest file.
No comments:
Post a Comment