测试互联网连接Android

时间:2013-05-15 21:10:58

标签: android networking

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

3 个答案:

答案 0 :(得分: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
{    }

答案 1 :(得分: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 :(得分:0)

使用此代码检查互联网连接,检查设备上的所有互联网连接。并且确保你已经在menifest中添加了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");
    }