如何在Android中以编程方式ping网站

时间:2018-09-29 18:29:00

标签: java android ping

我试图制作一个可以对网站或ip地址执行ping操作并仅在textview中显示ping编号的应用,我使用此代码来获取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();

    }

此代码只是给我多条吐司消息,就像在Windows Command中ping时一样,但是我如何才能获得ping编号,例如:85

1 个答案:

答案 0 :(得分:1)

我建议使用此库https://github.com/potterhsu/Pinger

设置 1.在root build.gradle中:

allprojects {
  repositories {
    ...
    maven { url 'https://jitpack.io' }
  }
}
  1. 在目标模块build.gradle中 dependencies { compile 'com.github.potterhsu:Pinger:v1.1' }

用法 1.直接在同步中ping:

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

2。 ping异步直到成功:

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异步直到失败:

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);