How to execute shell commands in Android

Source: Internet
Author: User

I. Methods
Copy codeThe Code is as follows :/**
* Execute a shell command and return the string value.
*
* @ Param cmd
* An array composed of command names and parameters (for example, {"/system/bin/cat", "/proc/version "})
* @ Param workdirectory
* Command Execution path (for example, "system/bin /")
* @ Return: A string composed of execution results
* @ Throws IOException
*/
Public static synchronized String run (String [] cmd, String workdirectory)
Throws IOException {
StringBuffer result = new StringBuffer ();
Try {
// Create an operation system (which can also be started by runtime.exe c)
// Runtime runtime = Runtime. getRuntime ();
// Process proc = runtime.exe c (cmd );
// InputStream inputstream = proc. getInputStream ();
ProcessBuilder builder = new ProcessBuilder (cmd );
InputStream in = null;
// Set a path (not required if the path is absolute)
If (workdirectory! = Null ){
// Set the working directory (same as above)
Builder. directory (new File (workdirectory ));
// Merge standard errors and standard output
Builder. redirectErrorStream (true );
// Start a new process
Process process = builder. start ();
// Read the standard output stream of the process
In = process. getInputStream ();
Byte [] re = new byte [1024];
While (in. read (re )! =-1 ){
Result = result. append (new String (re ));
}
}
// Close the input stream
If (in! = Null ){
In. close ();
}
} Catch (Exception ex ){
Ex. printStackTrace ();
}
Return result. toString ();
}

Ii. Purpose
Run top, ps, and other commands in Linux. You can also use adb to view the results.
1) The top command is as follows:
Copy codeThe Code is as follows: adb shell
$ Top-h
Top-h
Usage: top [-m max_procs] [-n iterations] [-d delay] [-s sort_column] [-t] [-h]
-M num Maximum number of processes to display. // display the Maximum number of processes.
-N num Updates to show before exiting. // refresh times
-D num Seconds to wait between updates. // refresh interval (5 Seconds by default)
-S col Column to sort by <cpu, vss, rss, thr> // sort by which Column
-T Show threads instead of processes. // display thread information instead of Process
-H Display this help screen. // Display the help document
$ Top-n 1
Top-n 1

The execution results will not be put on. The results are described as follows:Copy codeCode: User 35%, System 13%, IOW 0%, IRQ 0% // CPU usage
User 109 + Nice 0 + Sys 40 + Idle 156 + IOW 0 + IRQ 0 + SIRQ 1 = 306 // CPU usage
Pid cpu % S # thr vss rss pcy uid Name // process attributes
Xx % x xx
CPU usage:
User Process
System Process
Iow io wait time
IRQ hard interrupt time
CPU usage (the time occupied by a minimum time slice, in jiffies. Or process count ):
User running time in the User State, excluding the negative process with a priority value
CPU time occupied by a Nice process with a negative priority
Running time of Sys in core State
Idle other than I/O wait time
Iow io wait time
IRQ hard interrupt time
SIRQ Soft Interrupt time
Process attributes:
ID of the PID PROCESS IN THE SYSTEM
CPU % current instantaneous so CPU usage
The state of the S process, where S indicates sleep, R indicates running, Z indicates frozen, and N indicates that the priority value of the process is negative.
# Number of threads currently used by the THR Program
VSS Virtual Set Size Virtual memory consumption (including memory occupied by shared libraries)
RSS Resident Set Size actually uses physical memory (including memory occupied by shared libraries)
Pcy ooxx, don't know anything
ID of the user whose UID runs the current process
Name program Name android. process. media
// Ps: the memory usage has the following rules: VSS> = RSS> = PSS> = USS
// PSS Proportional Set Size physical memory actually used (Proportional allocation of memory occupied by the Shared Library)
// The physical memory occupied by the USS Unique Set Size process (excluding the memory occupied by the Shared Library)

In the attachment Android system-> android top.txt file, we will summarize it.
2) execute the code
Copy codeThe Code is as follows: // top Command
Public static final String [] TOP = {"/system/bin/top", "-n", "1 "};
// Execute top-n 1 now. We only need the second row (use the second row to obtain the CPU usage and precise data)
// Line 1: User 35%, System 13%, IOW 0%, IRQ 0% // CPU usage
// Row 2: User 109 + Nice 0 + Sys 40 + Idle 156 + IOW 0 + IRQ 0 + SIRQ 1 = 306
/// CPU usage
Public static synchronized String run (String [] cmd ){
String line = "";
InputStream is = null;
Try {
Runtime runtime = Runtime. getRuntime ();
Process proc = runtime.exe c (cmd );
Is = proc. getInputStream ();
// Change to BufferedReader
BufferedReader buf = new BufferedReader (new InputStreamReader (is ));
Do {
Line = buf. readLine ();
// There are several empty rows in front
If (line. startsWith ("User ")){
// Read the first row, and then read the next row.
Line = buf. readLine ();
Break;
}
} While (true );
If (is! = Null ){
Buf. close ();
Is. close ();
}
} Catch (IOException e ){
E. printStackTrace ();
}
Return line;
}
// Obtain the information obtained by the top command of the specified application
// Pid cpu % S # thr vss rss pcy uid Name // process attributes
// If the current application is not running, null is returned.
Public static synchronized String run (String [] cmd, String pkgName ){
String line = null;
InputStream is = null;
Try {
Runtime runtime = Runtime. getRuntime ();
Process proc = runtime.exe c (cmd );
Is = proc. getInputStream ();
// Change to BufferedReader
BufferedReader buf = new BufferedReader (new InputStreamReader (is ));
Do {
Line = buf. readLine ();
// Read the corresponding pkgName to jump out of the loop (or not found)
If (null = line | line. endsWith (pkgName )){
Break;
}
} While (true );
If (is! = Null ){
Buf. close ();
Is. close ();
}
} Catch (IOException e ){
E. printStackTrace ();
}
Return line;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.