Issue
I'm trying to do a written report on some code and I found one on Youtube. However I don't understand how this loop works. I understand that it must return a boolean
value which then goes into another method but if someone could breakdown what is happening it would be greatly appreciated.
public class Loop {
public static boolean isConnectedToInternet(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED)
return true;
}
}
}
return false;
}
}
Solution
I added some comments for understanding:
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(context.CONNECTIVITY_SERVICE);
//making the object
if (connectivityManager!=null){ //if it was instantiated
NetworkInfo[] info = connectivityManager.getAllNetworkInfo(); //it makes an array of all of the network info
if (info != null) { //if this worked (if there's info)
for (int i = 0; i < info.length; i++){ //looping through data
if (info[i].getState() == NetworkInfo.State.CONNECTED)
//if the state of any of the objects is equal to connected (if device is connected)
return true; //the device is online
}
}
}
return false; //the device is not online
Answered By - Nemo9703