user10210480
user10210480

Reputation: 21

How do I programmatically ping a website in Android

I trying to make an app that can get ping of websites or ip address and show just ping number in a textview,im using this code for get ping:

public void fExecutarPing(View view){
        Editable host = edtIP.getText();


    try {
        String cmdPing = "ping -c 1 -w 1 "+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){

            Toast.makeText(this, inputLinhe, Toast.LENGTH_SHORT).show();

        }


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

    }

this code just give me multi toast message like when you pinging in windows Command, but how can i just get ping number for example: 85

Upvotes: 2

Views: 6090

Answers (1)

Tung Duong
Tung Duong

Reputation: 1166

I recommend use this library https://github.com/potterhsu/Pinger

Setup 1. In root build.gradle:

allprojects {
  repositories {
    ...
    maven { url 'https://jitpack.io' }
  }
}
  1. In target module build.gradle dependencies { compile 'com.github.potterhsu:Pinger:v1.1' }

Usage 1. Ping directly in synchronization:

Pinger pinger = new Pinger();
pinger.ping("8.8.8.8", 3);

2. Ping in asynchronization until it is succeeded:

Pinger pinger = new Pinger();
pinger.setOnPingListener(new Pinger.OnPingListener() {
    @Override
    public void onPingSuccess() { ... }

    @Override
    public void onPingFailure() { ... }

    @Override
    public void onPingFinish() { ... }
});
pinger.pingUntilSucceeded("8.8.8.8", 5000);

3. Ping in asynchronization until it is failed:

Pinger pinger = new Pinger();
pinger.setOnPingListener(new Pinger.OnPingListener() {
    @Override
    public void onPingSuccess() { ... }

    @Override
    public void onPingFailure() { ... }

    @Override
    public void onPingFinish() { ... }
});
pinger.pingUntilFailed("8.8.8.8", 5000);

Upvotes: 2

Related Questions