如何解决检查网络是否稳定
我的应用程序使用 getInet4AddressByName() 方法。它需要打开互联网。为了检查 Wi-Fi 状态,我使用了 BroadcastReceiver 接收器。但是在打开 Wi-Fi 一段时间后会出现稳定的互联网并且该方法没有时间正常工作 getInet4AddressByName()
返回错误。如何跟踪稳定的 Internet 连接而不是 wi-fi 连接的存在?谢谢。
@Override
public void onReceive(Context context,Intent intent) {
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled()) {
tv.setText("You are connected");
} else {
tv.setText("You are NOT connected");
}
}
};
解决方法
您可以使用两种方法:
Google 推荐使用此代码块来检查互联网连接。因为设备即使连接到 WiFi 也可能没有互联网连接。 1 - 检查连接:
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
2 - 检查互联网:
public boolean internetIsConnected() {
try {
String command = "ping -c 1 google.com";
return (Runtime.getRuntime().exec(command).waitFor() == 0);
} catch (Exception e) {
return false;
}
}
向清单添加权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。