如何设置获取ping值的时间限制

时间:2017-09-05 11:10:36

标签: java android process ping

我正在开发一个应用程序来检查ping并更新TextView的值,但是当它在1000ms之前没有获得该值时,应用程序崩溃。有没有办法强制执行超时?

以下代码:

public void Start() {
    Ping();
    PingUpdate();
}

public void Ping() {
    String pingString;
    try {
        Process process = Runtime.getRuntime().exec("/system/bin/ping -c 1 " + url);
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        int i;
        char[] buffer = new char[4096];
        StringBuffer output = new StringBuffer();

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

        pingString = output.toString();

        pingString = pingString.substring(pingString.indexOf("time="), pingString.lastIndexOf("ping"));
        pingString = pingString.substring(pingString.indexOf("="), pingString.lastIndexOf("ms"));
        pingString = pingString.substring(1);

        TextView pingValue = (TextView)findViewById(R.id.Ping);
        pingValue.setText(pingString);

    }
    catch (IOException e) {
        // body.append("Error\n");
        e.printStackTrace();
    }
}

public void PingUpdate() {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            Ping();
            PingUpdate();
        }
    }, 1000);
}

0 个答案:

没有答案