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, eg "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
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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.