java - 试图解释一个检查网络连接的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;
}
}
解决方案
我添加了一些评论以供理解:
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
推荐阅读
- docker - 如何dockerzise beego应用程序
- .net - 使用 rotativa 将小村庄转换为 pdf 时出错
- python - 收集最旧的推文并记录发布的实时时间
- android - 尝试通过电子邮件 firebase 实现发送重置密码时应用程序崩溃
- ios - 将 SwiftUI 中的文本与背景属性相结合会产生错误,因为无法将“某些视图”类型的值转换为预期的参数类型“文本”?
- java - Thrift Java:不能使用保留语言关键字:“别名”
- xunit - xUnit - 异步列表的模拟方法返回 null
- pygame - 我想创建多个敌人但不断收到相同的错误代码
- c# - WPF C# MVVM ListView 未更新
- python - 在xampp中使用pip安装mysql时如何解决这个问题