Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run terminal command in Android application?

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?

like image 308
Osama Gamal Avatar asked May 16 '10 09:05

Osama Gamal


3 Answers

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;
}
like image 169
Josh Gao Avatar answered Nov 20 '22 22:11

Josh Gao


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

like image 1
Osama Gamal Avatar answered Nov 20 '22 21:11

Osama Gamal


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

like image 1
NickUnuchek Avatar answered Nov 20 '22 21:11

NickUnuchek