5

希望我可以做一个测试来验证互联网连接,我不想检查网络状态,因为它只检测我是否已经在我的设备上激活了互联网,y yo quiero revisar si es es posible conectarse a internet。类似于 ping 的东西。

4

3 回答 3

11

尝试以下操作:

public boolean checkOnlineState() {
    ConnectivityManager CManager =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo NInfo = CManager.getActiveNetworkInfo();
    if (NInfo != null && NInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

不要忘记访问权限

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

别的

if (InetAddress.getByName("www.xy.com").isReachable(timeout))
{    }
else
{    }
于 2013-05-15T21:15:20.883 回答
1

It does works for me:

To verify network availability:

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

To verify internet access:

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;
}
于 2014-03-07T17:02:18.840 回答
0

使用此代码检查互联网连接,它检查设备上的所有互联网连接。并确保您在清单中添加了 Internet 权限。

    boolean flag=false;
    ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null)
    {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null)
            for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED)
                {
                    flag=true;

                }

    }
    if(flag==true)
    {
         Log.e("TAG","Internet Is Connected");
    }
    else
    {
          Log.e("TAG","Internet Is Not Connected");
    }
于 2015-04-09T06:35:12.960 回答