Running ping command in the shell from app

2019-02-21 07:03发布

I have found source code that gives an opportunity to run a shell command from the app, and, as I can understand, returns a string with the executed command result:

http://code.google.com/p/netmeterled/source/browse/trunk/src/com/britoso/cpustatusled/utilclasses/ShellCommand.java?r=29

I have tried to execute "ping -c 3 www.google.com", but the given method returns "Error: null". The way I execute the command is:

ShellCommand cmd = new ShellCommand();
CommandResult r = cmd.sh.runWaitFor("ping -c 5 www.google.com");
String text;
if (!r.success()) {
    text = "Error:\n" + r.stderr;
}
else {
    text ="Ping test results:\n" + r.stdout;
}
log(text);

Where is the problem?

2条回答
闹够了就滚
2楼-- · 2019-02-21 07:58

You have probably solved this by now. But telling you you shouldn't do it seemed like no answer to me. Obviously if the ping command doesn't exist you can't call it and you can handle the error. But if it does, wow!

Here is a way to do it. Works on the emulator 2.1 anyway. The emulator likes to be started after you have a good Internet connection though. If you start the emulator and change your connection somehow, it may not work after that. I didn't need any permissions to do it either on the emulator.

public class Rooted extends Activity {
    EditText body;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        body = (EditText)findViewById(R.id.bodyEditText);
        try {
        Process process = Runtime.getRuntime().exec("/system/bin/ping -c 1 betterpaving.com");
        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();
        body.append(output.toString()+"\n");
        } 
        catch (IOException e) {
            body.append("Error\n");
            e.printStackTrace();
            } 
        }//oncreate

    //TODO: Fill In Methods Etc.

    //"ping -c 1 betterpaving.com" try this sometime
}//class

It's different from yours anyway and needs to be put somewhere besides the create block, but...

查看更多
够拽才男人
3楼-- · 2019-02-21 08:07

Do you have Internet permission for your app? And is the device connected to the Internet? Is there any output in the Logcat?

This question shows a one method you could use to ping from Java, without needing to run the shell command.

查看更多
登录 后发表回答