我有这个代码,我必须避免DD异常“最近的变量被重新定义”。但我也必须避免创建另一个return语句。我不知道该怎么做。如果有人可以帮助我,那将非常有帮助。
DD异常代码
public static boolean hasActiveInternetConnection() {
int returnVal = 1;
try {
final Process ping = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
returnVal = ping.waitFor();
} catch (final java.io.IOException | InterruptedException e) {
Log.e(TAG, e.getMessage());
}
return returnVal == 0;
}
具有双重返回异常的代码
public static boolean hasActiveInternetConnection() {
try {
final Process ping = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
final int returnVal = ping.waitFor();
return returnVal == 0;
} catch (final java.io.IOException | InterruptedException e) {
Log.e(TAG, e.getMessage());
}
return false;
}
谢谢!
答案 0 :(得分:2)
public boolean isNetworkActive() {
try {
Process ping = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
return ping.waitFor()==0? true : false;
} catch (final java.io.IOException | InterruptedException e) {
return false;
}
}
顺便说一下,这不是你在Android上测试网络连接的方法,这里有一个更有帮助的方法:
public static boolean checkNetworkStatus(Context context) {
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean networkIsMobile = false;
boolean networkIsWiFi = false;
if (wifi != null && wifi.isAvailable() && wifi.isConnected()) {
networkIsWiFi = true;
}
if (mobile != null && mobile.isAvailable() && mobile.isConnected()) {
networkIsMobile = true;
}
boolean networkActive = networkIsMobile || networkIsWiFi;
return networkActive;
} // End of checkNetworkStatus
PS:我认为pingFor == 0表示网络和pingFor == 1表示没有网络,如果是相反的话,请切换它们