检查安卓的互联网连接是否有效

2022-09-04 05:15:47

我正在尝试在我的应用程序中编写一个部分,该部分将区分活动Wifi连接和实际连接到互联网。使用连接管理器找出是否有有效的Wifi连接非常简单,但是每次我尝试测试是否可以在Wifi连接时连接到网站,但没有互联网连接,我最终陷入了无限循环。
我试图ping谷歌,但这最终以同样的方式结束:

Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = 5;
try {
    returnVal = p1.waitFor();
} catch (InterruptedException e) {
    e.printStackTrace();
}
boolean reachable = (returnVal==0);
return reachable;

我也尝试了这个代码:

if (InetAddress.getByName("www.xy.com").isReachable(timeout))
{    }
else
{    }

但我无法得到是可以工作。


答案 1

它确实对我有用:

要验证网络可用性,请执行以下操作:

private Boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}

要验证互联网访问:

public Boolean isOnline() {
    try {
        Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
        int returnVal = p1.waitFor();
        boolean reachable = (returnVal==0);
        return reachable;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

答案 2

我用这个:

public static void isNetworkAvailable(Context context){
    HttpGet httpGet = new HttpGet("http://www.google.com");
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    try{
        Log.d(TAG, "Checking network connection...");
        httpClient.execute(httpGet);
        Log.d(TAG, "Connection OK");
        return;
    }
    catch(ClientProtocolException e){
        e.printStackTrace();
    }
    catch(IOException e){
        e.printStackTrace();
    }

    Log.d(TAG, "Connection unavailable");
}

它来自另一个堆栈溢出答案,但我找不到它。

编辑:

最后我找到了:https://stackoverflow.com/a/1565243/2198638


推荐