Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to run shell commands on android programmatically?

Tags:

linux

android

Is there any way to run terminal commands on my application and then access the data on my UI? Specifically top.

like image 949
Shouvik Avatar asked Jul 28 '10 06:07

Shouvik


People also ask

Can you use a shell in Android?

Open the Command Shell on an Remote Endpoint Using the Android Access Console. Remote command shell enables privileged users to open a virtual command line interface on remote computers. Users can then type locally but have the commands executed on the remote system. You can work from multiple shells.

How do I execute a shell command in Kotlin?

Start by creating a Shell: val shell = Shell("sh") ``` Then invoke the `run()` method passing in shell command you want executed as a string: ```kotlin val result = shell. run("echo 'Hello, World! '")


2 Answers

Check out Log Collector as an example. Here is the relevant file.

The key is here:

ArrayList<String> commandLine = new ArrayList<String>(); commandLine.add("logcat");//$NON-NLS-1$ [...]  Process process = Runtime.getRuntime().exec(commandLine); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); 
like image 113
EboMike Avatar answered Oct 03 '22 13:10

EboMike


Okay this is what exactly worked for me just in case anyone needs it in the future... :)

Surround in try and catch

try {     Process process = Runtime.getRuntime().exec("top -n 1 -d 1");     BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); } catch (InterruptedException e) {     e.printStackTrace(); } 
like image 40
Shouvik Avatar answered Oct 03 '22 13:10

Shouvik