2

I'm trying to execute a shell command in an android app (Java) and read the output. I can read the output of most commands but I am unable to get anything when I use a pipe in the command. The device is rooted.

I've found this but it doesn't want to work on Android. I've tried output redirects, e.g. "2>&1" at the end of the command but no luck.

Thanks in advance!

Working Command

pm list packages

Not Working Command

pm list packages | grep com.myapp

Code:

public String executeCommand(String command) {
    String output = "";

        InputStream inputStream = Runtime.getRuntime().exec(command).getInputStream();

        while( inputStream.available() <= 0) 
            try { Thread.sleep(500); } catch(Exception ex) {}

        java.util.Scanner s = new java.util.Scanner(inputStream);
        while(s.hasNext())
            output += s.nextLine() + "\n";

            return output; 
}

Try and catch blocks omitted for brevity

Community
  • 1
  • 1
D. Gibbs
  • 540
  • 3
  • 17

2 Answers2

2

It's been over two years now, but one can try this:

Instead:

Runtime.getRuntime().exec(command);

call:

String[] shell = {"sh", "-c", command};
Runtime.getRuntime().exec(shell);
sZpak
  • 247
  • 10
1

My bet is that grep is not installed on your device. You can check it by starting up an ADB shell and typing in grep and you should probably see

> adb shell
$ grep
grep: not found

I suggest you filter the results on your own in Java as not all devices have grep preinstalled.

Bojan Kseneman
  • 15,488
  • 2
  • 54
  • 59
  • grep is installed on the device and is working when run on the shell. It outputs to the terminal just fine, just not to the java program. – D. Gibbs May 07 '15 at 15:49
  • 1
    Nonetheless, if you want to publish this app and it is going to be used by users, don't use grep as it is not installed on all devices. If you use it for yourself, then ok – Bojan Kseneman May 07 '15 at 15:51