问题描述
我的应用程序使用 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" />