首页 > 解决方案 > 试图解释一个检查网络连接的java嵌套循环

问题描述

我正在尝试对一些代码进行书面报告,我在 Youtube 上找到了一个。但是我不明白这个循环是如何工作的。我知道它必须返回一个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;
    }
}

标签: javafor-loopif-statementconnection

解决方案


我添加了一些评论以供理解:

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

推荐阅读