Test Internet Connection Android

2019-01-15 03:30发布

Wish I could do a test to verify internet connection, I don't want check network state, because it only detects if I have activated internet on my device, y yo quiero revisar si es posible conectarse a internet. Something like a ping.

3条回答
ゆ 、 Hurt°
2楼-- · 2019-01-15 03:47

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;
}
查看更多
来,给爷笑一个
3楼-- · 2019-01-15 03:51

Use This code to check internet connection, it check all the internet connection over device. And Make Sure you have added Internet Permission in menifest.

    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");
    }
查看更多
Deceive 欺骗
4楼-- · 2019-01-15 03:56

Try following:

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

dont forget the access

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

else

if (InetAddress.getByName("www.xy.com").isReachable(timeout))
{    }
else
{    }
查看更多
登录 后发表回答