Android代码执行adb shell命令

好久没写随笔了,几乎忘记了这个技术点,今天特地记录下:

前提:有系统root权限

方法一:

new Thread(new Runnable() {
@Override
public void run() {
String content = "";
BufferedReader reader = null;
InputStream is = null;
try {
java.lang.Process process = Runtime.getRuntime().exec("adb shell ps | grep NAG");
is = process.getInputStream();
reader = new BufferedReader(new InputStreamReader(is));
StringBuffer output = new StringBuffer();
int read;
char[] buffer = new char[4096];
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
content = output.toString();
VoiceLog.logInfo(TAG, "checkNagNew content " + content);
} catch (Exception e) {
e.printStackTrace();
VoiceLog.logInfo(TAG, "read logcat process failed. message: " + e.getMessage());
} finally {
if (null != is) {
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();


方法二:
new Thread(new Runnable() {
@Override
public void run() {
FileOutputStream os = null;
Process p = null;
try {
p = Runtime.getRuntime().exec("adb shell ps | grep NAG");
InputStream is = p.getInputStream();
os = new FileOutputStream("/sdcard/00.log");
int len = 0;
byte[] buf = new byte[1024];
while ((-1 != (len = is.read(buf)))) {
os.write(buf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
os.flush();
os.close();
}catch (Exception e){
e.printStackTrace();
}

}
}
}).start();

PS: 命令要加adb shell, 不然打印结果是不会出来的
原文地址:https://www.cnblogs.com/mengdao/p/14544660.html