Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art
Running an External/Native Unix/Linux CommandBack to Android Cookbook Home | Up to Chapter: Other Programming Languages

Author: Amir Alagic ('Alagic Amir')
In Published Edition? No
FormatLanguage: WikiFormat

Running an External/Native Unix/Linux Command


Sometimes it can be convenient to start one of the Linux commands that are available on the phone such as rm, sync, top, uptime...


To run Linux commands available on the Android OS you should use classes that are available in standard Java and are used to start external processes. First you have to know which command you want to run and then get/obtain Runtime object and then execute the native command in a separate native process. Often you will need to read results and to do that use streams to do that.


Since Java is such a powerful language it is pretty simple to start external processes.

With AndroZip File Manager or other you can find Linux commands in ./system/bin folder. One of the commands is ls which lists the files (and subfolders) in a folder. To run this command we will send its path to the Runtime.exec method.

You can not create a Runtime object directly since it is a singleton; to obtain its instance you call the static getRuntime() method and then pass the path to the Linux command you want to run.

	Process process = Runtime.getRuntime().exec("/system/bin/ls");

The Process class is used above to create the process; it will also help us read from the process and we obtain an InputStream that is connected to the standard output stream (stdout) of the native process represented by this object.

	DataInputStream osRes = new DataInputStream(process.getInputStream());

Then we create BufferedReader object which will help us to read results line by line.

	BufferedReader reader = new BufferedReader(new InputStreamReader(osRes));	
	String line;
	while ((line = reader.readLine()) != null || reader.read() !=-1) {

		Log.i("Reading command result", line);


And as you see we will read all lines and show them on LogCat console. You can see the output for example in your Eclipse IDE.

You could, of course, capture the output of any system command back into your program and either parse it for display in e.g., a ListView, or display it as text in a TextView.

See Also