How to run terminal command in Android application?

27,532

Solution 1

You have to use reflection to call android.os.Exec.createSubprocess():

public String ls () {
    Class<?> execClass = Class.forName("android.os.Exec");
    Method createSubprocess = execClass.getMethod("createSubprocess", String.class, String.class, String.class, int[].class);
    int[] pid = new int[1];
    FileDescriptor fd = (FileDescriptor)createSubprocess.invoke(null, "/system/bin/ls", "/", null, pid);

    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fd)));
    String output = "";
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            output += line + "\n";
        }
    }
    catch (IOException e) {}
    return output;
}

Solution 2

Try this answer there is way to run shell commands on android programmatically https://stackoverflow.com/a/3350332/2425851

Solution 3

Different solutions could be found here: http://code.google.com/p/market-enabler/wiki/ShellCommands I've not tested them yet.

Share:
27,532
Osama Gamal
Author by

Osama Gamal

Updated on July 09, 2022

Comments

  • Osama Gamal
    Osama Gamal almost 2 years

    How to send a command to the terminal through android app and get the output back? For example, sending "ls /" and getting the output to print it in the GUI?

  • Josh Gao
    Josh Gao almost 14 years
    Oops, that'd be the reflected class.
  • ademar111190
    ademar111190 over 10 years
    I'm getting "java.lang.ClassNotFoundException: android.os.Exec"