Ping via android

2

Is there a way to show the average ping on android? I saw some tutorials but the most I got was this:

public void fExecutarPing(View view){
    List<String> listaResponstaPing = new ArrayList<String>();
    ArrayAdapter<String> adapterLista = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
            listaResponstaPing);

    try {
        String cmdPing = "ping -c 4 " + host;
        Runtime r = Runtime.getRuntime();
        Process p = r.exec(cmdPing);
        BufferedReader in = new BufferedReader( new InputStreamReader(p.getInputStream()));
        String inputLinhe;

        while((inputLinhe = in.readLine())!= null){
            listaResponstaPing.add(inputLinhe);
            //adiciona para cada linha
            listaPing.setAdapter(adapterLista);
        }

    } catch (Exception e) {
        Toast.makeText(this, "Erro: "+e.getMessage().toString(), Toast.LENGTH_SHORT).show();

    }


}

That shows the ping, along with the rest of the information. And what I need is to show only the average ping. How to do?

    
asked by anonymous 14.03.2017 / 17:25

1 answer

2

Let's take this result line into consideration:

  

4 packets transmitted, 4 received, 0% packet loss, 3004ms time

What interests you is the following part: 4 received .

To get this number, we will use the indexOf

Here's an example:

private Integer getPacotesRecebidos(final String fulltext){
    /**
     * Parte inicial do texto que vamos buscar na fullText
     */
    final String textStart = "packets transmitted,";
    /**
     * Pegamos o indice onde começa esta parte do texto mais o seu tamanho
     */
    int start_ = fulltext.indexOf(textStart) + textStart.length();
    /**
     * Pegamos o indice onde começa esta parte
     */
    int end_ = fulltext.indexOf("received,");

    /**
     * Através do substring, pegamos a parte específica da string
     */
    final String s = fulltext.substring(start_, end_);

    /**
     * Transformamos a String em um Integer (trim: remove os espaços em branco)
     */
    return Integer.valueOf(s.trim());

}

Usage :

@Override
public void onClick(View v) {

    try{
        String cmdPing = "ping -c 4 www.google.com";
        Runtime r = Runtime.getRuntime();
        Process p = r.exec(cmdPing);
        BufferedReader in = new BufferedReader( new InputStreamReader(p.getInputStream()));
        String inputLinhe;
        /**
         * Vamos pegar o resultado!
         */
        final StringBuffer buff = new StringBuffer();
        while((inputLinhe = in.readLine())!= null){
            buff.append(inputLinhe);
        }

        final Integer pacotesRecebidos = getPacotesRecebidos(buff.toString());

        Toast.makeText(getApplicationContext(), "Pacotes Recebidos: "+pacotesRecebidos, Toast.LENGTH_SHORT).show();

    }catch (final Exception e){
        e.printStackTrace();
    }


}
    
14.03.2017 / 18:07