如何在Android中ping服务器?

时间:2013-07-05 16:08:22

标签: android connection boolean ping

如何ping Android中的某些Web服务器来测试我是否有Internet连接? 所以我需要ping给定网站的方法,如果我没有互联网则返回false,如果有的话,则返回true。

2 个答案:

答案 0 :(得分:9)

请参阅此方法,这是检查与给定服务器的连接的最佳方法:

http://developer.android.com/reference/java/net/InetAddress.html#isReachable(int)

答案 1 :(得分:0)

使用这些方法ping服务器

public static void inSomeWhere()
    {
        String pingResult = getPingResult("168.126.63.1");
        boolean isNetOk = true;
        if (pingResult == null) {
            // not reachable!!!!!
            isNetOk = false;
        }

    }


    public static String getPingResult(String a) {
        String str = "";
        String result = "";
        BufferedReader reader = null;
        char[] buffer = new char[4096];
        StringBuffer output = new StringBuffer();

        try {
            Runtime r = Runtime.getRuntime();
            Process process = r.exec("/system/bin/ping -c 3 " + a);
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            int i;

            while ((i = reader.read(buffer)) > 0)
                output.append(buffer, 0, i);


            str = output.toString();

            final String[] b = str.split("---");
            final String[] c = b[2].split("rtt");

            if (b.length == 0 || c.length == 0)
                return null;

            if(b.length == 1 || c.length == 1)
                return null;

            result = b[1].substring(1, b[1].length()) + c[0] + c[1].substring(1, c[1].length());

        } catch (IOException e) {
            return null;
        } catch (Exception e) {
            return null;
        }
        finally
        {
            if(reader != null)
            {
                try{reader.close();}catch(IOException ie){}
            }
        }

        return result;
    }