试图解释一个检查网络连接的 java 嵌套循环
Trying to explain a a java nested loop which checks for a network connection
我正在尝试对一些代码做一份书面报告,我在 Youtube 上找到了一个。但是我不明白这个循环是如何工作的。我知道它必须 return 一个 boolean
值,然后进入另一个方法,但如果有人能分解正在发生的事情,我将不胜感激。
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;
}
}
我添加了一些评论以供理解:
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
我正在尝试对一些代码做一份书面报告,我在 Youtube 上找到了一个。但是我不明白这个循环是如何工作的。我知道它必须 return 一个 boolean
值,然后进入另一个方法,但如果有人能分解正在发生的事情,我将不胜感激。
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;
}
}
我添加了一些评论以供理解:
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