如何在android程序中执行adb shell命令
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在android程序中执行adb shell命令相关的知识,希望对你有一定的参考价值。
一、方法代码如下:
/**
* 执行一个shell命令,并返回字符串值
*
* @param cmd
* 命令名称&参数组成的数组(例如:"/system/bin/cat", "/proc/version")
* @param workdirectory
* 命令执行路径(例如:"system/bin/")
* @return 执行结果组成的字符串
* @throws IOException
*/
public static synchronized String run(String[] cmd, String workdirectory)
throws IOException
StringBuffer result = new StringBuffer();
try
// 创建操作系统进程(也可以由Runtime.exec()启动)
// Runtime runtime = Runtime.getRuntime();
// Process proc = runtime.exec(cmd);
// InputStream inputstream = proc.getInputStream();
ProcessBuilder builder = new ProcessBuilder(cmd);
InputStream in = null;
// 设置一个路径(绝对路径了就不一定需要)
if (workdirectory != null)
// 设置工作目录(同上)
builder.directory(new File(workdirectory));
// 合并标准错误和标准输出
builder.redirectErrorStream(true);
// 启动一个新进程
Process process = builder.start();
// 读取进程标准输出流
in = process.getInputStream();
byte[] re = new byte[1024];
while (in.read(re) != -1)
result = result.append(new String(re));
// 关闭输入流
if (in != null)
in.close();
catch (Exception ex)
ex.printStackTrace();
return result.toString();
二、用途
执行Linux下的top、ps等命令,这些命令你也通过adb可以执行查看效果。
1)top命令如下:
复制代码 代码如下:
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. // 最多显示多少个进程
-n num Updates to show before exiting. // 刷新次数
-d num Seconds to wait between updates. // 刷新间隔时间(默认5秒)
-s col Column to sort by <cpu,vss,rss,thr> // 按哪列排序
-t Show threads instead of processes. // 显示线程信息而不是进程
-h Display this help screen. // 显示帮助文档
$ top -n 1
top -n 1
就不把执行效果放上来了,总之结果表述如下:
代码如下:
User 35%, System 13%, IOW 0%, IRQ 0% // CPU占用率
User 109 + Nice 0 + Sys 40 + Idle 156 + IOW 0 + IRQ 0 + SIRQ 1 = 306 // CPU使用情况
PID CPU% S #THR VSS RSS PCY UID Name // 进程属性
xx xx% x xx xx xx xx xx xx
CPU占用率:
User 用户进程
System 系统进程
IOW IO等待时间
IRQ 硬中断时间
CPU使用情况(指一个最小时间片内所占时间,单位jiffies。或者指所占进程数):
User 处于用户态的运行时间,不包含优先值为负进程
Nice 优先值为负的进程所占用的CPU时间
Sys 处于核心态的运行时间
Idle 除IO等待时间以外的其它等待时间
IOW IO等待时间
IRQ 硬中断时间
SIRQ 软中断时间
进程属性:
PID 进程在系统中的ID
CPU% 当前瞬时所以使用CPU占用率
S 进程的状态,其中S表示休眠,R表示正在运行,Z表示僵死状态,N表示该进程优先值是负数。
#THR 程序当前所用的线程数
VSS Virtual Set Size 虚拟耗用内存(包含共享库占用的内存)
RSS Resident Set Size 实际使用物理内存(包含共享库占用的内存)
PCY OOXX,不知道什么东东
UID 运行当前进程的用户id
Name 程序名称android.process.media
// ps:内存占用大小有如下规律:VSS >= RSS >= PSS >= USS
// PSS Proportional Set Size 实际使用的物理内存(比例分配共享库占用的内存)
// USS Unique Set Size 进程独自占用的物理内存(不包含共享库占用的内存)
在附件Android系统->android top.txt文件内,自个总结的。
2)执行代码
代码如下:
// top命令
public static final String[] TOP = "/system/bin/top", "-n", "1" ;
// 现在执行top -n 1,我们只需要第二行(用第二行求得CPU占用率,精确数据)
// 第一行:User 35%, System 13%, IOW 0%, IRQ 0% // CPU占用率
// 第二行:User 109 + Nice 0 + Sys 40 + Idle 156 + IOW 0 + IRQ 0 + SIRQ 1 = 306
// // CPU使用情况
public static synchronized String run(String[] cmd)
String line = "";
InputStream is = null;
try
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(cmd);
is = proc.getInputStream();
// 换成BufferedReader
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
do
line = buf.readLine();
// 前面有几个空行
if (line.startsWith("User"))
// 读到第一行时,我们再读取下一行
line = buf.readLine();
break;
while (true);
if (is != null)
buf.close();
is.close();
catch (IOException e)
e.printStackTrace();
return line;
// 获取指定应用的top命令获取的信息
// PID CPU% S #THR VSS RSS PCY UID Name // 进程属性
// 如果当前应用不在运行则返回null
public static synchronized String run(String[] cmd, String pkgName)
String line = null;
InputStream is = null;
try
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(cmd);
is = proc.getInputStream();
// 换成BufferedReader
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
do
line = buf.readLine();
// 读取到相应pkgName跳出循环(或者未找到)
if (null == line || line.endsWith(pkgName))
break;
while (true);
if (is != null)
buf.close();
is.close();
catch (IOException e)
e.printStackTrace();
return line;
参考技术A package net.gimite.nativeexe;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.gimite.nativeexe.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class MainActivity extends Activity
private TextView outputView;
private Button localRunButton;
private EditText localPathEdit;
private Handler handler = new Handler();
private EditText urlEdit;
private Button remoteRunButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
outputView = (TextView)findViewById(R.id.outputView);
localPathEdit = (EditText)findViewById(R.id.localPathEdit);
localRunButton = (Button)findViewById(R.id.localRunButton);
localRunButton.setOnClickListener(onLocalRunButtonClick);
private OnClickListener onLocalRunButtonClick = new OnClickListener()
public void onClick(View v)
String output = exec(localPathEdit.getText().toString());
output(output);
// try
//
// // Process process = Runtime.getRuntime().exec(localPathEdit.getText().toString());
//
// catch (IOException e)
// // TODO Auto-generated catch block
// e.printStackTrace();
//
;
// Executes UNIX command.
private String exec(String command)
try
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0)
output.append(buffer, 0, read);
reader.close();
process.waitFor();
return output.toString();
catch (IOException e)
throw new RuntimeException(e);
catch (InterruptedException e)
throw new RuntimeException(e);
private void download(String urlStr, String localPath)
try
URL url = new URL(urlStr);
HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
urlconn.setRequestMethod("GET");
urlconn.setInstanceFollowRedirects(true);
urlconn.connect();
InputStream in = urlconn.getInputStream();
FileOutputStream out = new FileOutputStream(localPath);
int read;
byte[] buffer = new byte[4096];
while ((read = in.read(buffer)) > 0)
out.write(buffer, 0, read);
out.close();
in.close();
urlconn.disconnect();
catch (MalformedURLException e)
throw new RuntimeException(e);
catch (IOException e)
throw new RuntimeException(e);
private void output(final String str)
Runnable proc = new Runnable()
public void run()
outputView.setText(str);
;
handler.post(proc);
要加入权限本回答被提问者采纳
Android程序中如何执行shell脚本
在做Android应用时,经常需要执行shell脚本,以快速实现某些功能;
在Android应用程序中执行shell脚本可以省去一大堆繁琐的代码,还可以避免不必要的错误;
比如:拷贝文件夹时,可以执行shell命令中的 cp 命令达到目的;而在代码中实现拷贝文件夹时,不仅需要编写一大堆繁琐的代码,还容易陷入递归死循环的错误中;
比如:获取文件系统的读写权限,只需要执行shell脚本中一句 mount -o rw,remount / 就能轻松搞定;
比如:删除文件夹下某一个文件、或者某一类文件、或者全部文件,只需要执行shell脚本中的一句 rm -f *(利用*通配符进行匹配) 就能轻松搞定;
再比如:静默安装时,只需要执行shell脚本中一句 pm install -r 便可达到目的;
如果这些都用代码来实现,不仅代码量增加,还容易造成很多bug,吃力不讨好!
如果能在android应用中执行shell脚本来达到目的,可以省去一大堆代码,避免很多易犯的错误,简洁高效,何乐而不为呢?!
下面给出一个在Android应用中执行shell脚本的工具类的示例,供大家参考:
1 package com.example.test; 2 3 import java.io.BufferedReader; 4 import java.io.DataOutputStream; 5 import java.io.IOException; 6 import java.io.InputStreamReader; 7 8 import android.util.Log; 9 10 /** 11 * 执行shell脚本工具类 12 * @author Mountain 13 * 14 */ 15 public class CommandExecution { 16 17 public static final String TAG = "CommandExecution"; 18 19 public final static String COMMAND_SU = "su"; 20 public final static String COMMAND_SH = "sh"; 21 public final static String COMMAND_EXIT = "exit\n"; 22 public final static String COMMAND_LINE_END = "\n"; 23 24 /** 25 * Command执行结果 26 * @author Mountain 27 * 28 */ 29 public static class CommandResult { 30 public int result = -1; 31 public String errorMsg; 32 public String successMsg; 33 } 34 35 /** 36 * 执行命令—单条 37 * @param command 38 * @param isRoot 39 * @return 40 */ 41 public static CommandResult execCommand(String command, boolean isRoot) { 42 String[] commands = {command}; 43 return execCommand(commands, isRoot); 44 } 45 46 /** 47 * 执行命令-多条 48 * @param commands 49 * @param isRoot 50 * @return 51 */ 52 public static CommandResult execCommand(String[] commands, boolean isRoot) { 53 CommandResult commandResult = new CommandResult(); 54 if (commands == null || commands.length == 0) return commandResult; 55 Process process = null; 56 DataOutputStream os = null; 57 BufferedReader successResult = null; 58 BufferedReader errorResult = null; 59 StringBuilder successMsg = null; 60 StringBuilder errorMsg = null; 61 try { 62 process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH); 63 os = new DataOutputStream(process.getOutputStream()); 64 for (String command : commands) { 65 if (command != null) { 66 os.write(command.getBytes()); 67 os.writeBytes(COMMAND_LINE_END); 68 os.flush(); 69 } 70 } 71 os.writeBytes(COMMAND_EXIT); 72 os.flush(); 73 commandResult.result = process.waitFor(); 74 //获取错误信息 75 successMsg = new StringBuilder(); 76 errorMsg = new StringBuilder(); 77 successResult = new BufferedReader(new InputStreamReader(process.getInputStream())); 78 errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream())); 79 String s; 80 while ((s = successResult.readLine()) != null) successMsg.append(s); 81 while ((s = errorResult.readLine()) != null) errorMsg.append(s); 82 commandResult.successMsg = successMsg.toString(); 83 commandResult.errorMsg = errorMsg.toString(); 84 Log.i(TAG, commandResult.result + " | " + commandResult.successMsg 85 + " | " + commandResult.errorMsg); 86 } catch (IOException e) { 87 String errmsg = e.getMessage(); 88 if (errmsg != null) { 89 Log.e(TAG, errmsg); 90 } else { 91 e.printStackTrace(); 92 } 93 } catch (Exception e) { 94 String errmsg = e.getMessage(); 95 if (errmsg != null) { 96 Log.e(TAG, errmsg); 97 } else { 98 e.printStackTrace(); 99 } 100 } finally { 101 try { 102 if (os != null) os.close(); 103 if (successResult != null) successResult.close(); 104 if (errorResult != null) errorResult.close(); 105 } catch (IOException e) { 106 String errmsg = e.getMessage(); 107 if (errmsg != null) { 108 Log.e(TAG, errmsg); 109 } else { 110 e.printStackTrace(); 111 } 112 } 113 if (process != null) process.destroy(); 114 } 115 return commandResult; 116 } 117 118 }
以上是关于如何在android程序中执行adb shell命令的主要内容,如果未能解决你的问题,请参考以下文章