Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Running Shell Commands from Your Application

Published? true
FormatLanguage: WikiFormat

Problem:

You need to run a shell command from your application (for instance pwd, ls etc).

Solution:

Using the exec() method of the Runtime class we can provide the shell command we wish to run as an argument.

Discussion:

Applications can not create an instance of Runtime class, but they can get an instance by invoking getRuntime() method. Using this instance we call the exec method which executes the specified program in a separate native process. It takes the name of the program to execute as an argument. The exec method returns the new Process object that represents the native process.

As an example, we run the ps command that lists all the process running on the system. The full location of the command is specified (/system/bin/ps) as an argument to exec().

We get the output of the command and return the String. process.waitFor() is used to wait for the command to finish executing.


try {
	Process process = Runtime.getRuntime().exec("/system/bin/ps");
	InputStreamReader reader = new InputStreamReader(process.getInputStream());
	BufferedReader bufferedReader = new BufferedReader(reader);
	int numRead;
	char[] buffer = new char[5000];
	StringBuffer commandOutput = new StringBuffer();
	while ((numRead = bufferedReader.read(buffer)) > 0) {
		commandOutput.append(buffer, 0, numRead);
    }
    bufferedReader.close();
    process.waitFor();

    return commandOutput.toString();
} catch (IOException e) {
    throw new RuntimeException(e);
} catch (InterruptedException e) {
    throw new RuntimeException(e);
}

Here is how the output of the ps command looks:

Download:

The source code for this project can be downloaded from https://docs.google.com/leaf?id=0B_rESQKgad5LNTkxMDIyYTgtMzlmMS00ZDViLThkOTUtYWY4MjQ5NGY1NzFk&hl=en_US.