Test Internet Connection Android

前端 未结 3 604
失恋的感觉
失恋的感觉 2020-12-06 07:55

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 revis

相关标签:
3条回答
  • 2020-12-06 08:28

    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
    {    }
    
    0 讨论(0)
  • 2020-12-06 08:31

    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;
    }
    
    0 讨论(0)
  • 2020-12-06 08:40

    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");
        }
    
    0 讨论(0)
提交回复
热议问题