سؤال

I'm quite new to Android Programming and I'm not that experienced with Java/Android Programming. I wanted to make an app, which pings an address entered by the user.

So I found a quit nice script, which does an ICMP Ping Request to an address and gives back the output of the command-line. (In fact it's just the Ping-command, which is ran in an process):

public String ping(String url){
    int count = 0;
    String str = "";
    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();
        //int time = Integer.parseInt(output[10])
        // body.append(output.toString()+"\n");
        str = output.toString();
        str = str.substring(str.indexOf("time="), str.indexOf("ms"));
        //str = output.toString();
        // Log.d(TAG, str);

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

Output:

time = 43

However I don't really understand what everything does here, because it's an script from the Internet. Because I'm just interrested in the time of the response, I want to parse it and turn it into an Integer.

In my opinion there are two possibilities

  • Modify the ping command to just give back the time
  • Parse the Integer of the time out of the String

I never worked with that kind of stuff, so I wanted to ask you guys if you could help me. :)

هل كانت مفيدة؟

المحلول

You can do it in few ways:

1

str = str.substring(str.indexOf("=") + 1, str.indexOf("ms")).trim();
int result = Integer.valueOf(str);

2

str = str.replace("time=", "").replace("ms", "").trim();
int result = Integer.valueOf(str);

3

Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(output.toString());
matcher.find();
String result = matcher.group();
int result = Integer.valueOf(str);

4

str = str.replaceAll("\\D+","");
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top