检查Android的有效互联网连接

use*_*944 12 java networking android ping wifi

我正在尝试在我的应用程序中编写一个部分,以区分Active Wifi连接和实际连接到Internet.使用连接管理器查明是否存在有效的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;
Run Code Online (Sandbox Code Playgroud)

我也试过这段代码:

if (InetAddress.getByName("www.xy.com").isReachable(timeout))
{    }
else
{    }
Run Code Online (Sandbox Code Playgroud)

但我无法得到isReachable工作.

Mus*_*laa 25

它对我有用:

要验证网络可用性:

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

验证互联网访问:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 使用ping方法警告!这在我测试的大多数设备上都很好用,但在S4 Mini上却不行. (2认同)

Brt*_*tle 10

我用这个:

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");
}
Run Code Online (Sandbox Code Playgroud)

它来自另一个stackoverflow答案,但我找不到它.

编辑:

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