项目中要用 adb shell 的linux命令来停止进程,要获取到执行命令返回的数据。其实非常简单,
不多说直接上代码:
public void exit() {
Process process;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
OutputStream os = null;
DataOutputStream ds = null;
String cmd = " ps ";// ok
try {
// 使用Runtime来执行command,生成Process对象
Runtime runtime = Runtime.getRuntime();
process = runtime.exec(cmd);
// 取得命令结果的输出流
// process.waitFor();
is = process.getInputStream();
// 用一个读输出流类去读
isr = new InputStreamReader(is);
// 用缓冲器读行
br = new BufferedReader(isr);
String line = null;
// StringBuffer sb = new StringBuffer();
// 获取ps所有数据
ArrayList<String> as = new ArrayList<String>();
while ((line = br.readLine()) != null) {
System.out.println(line);
as.add(line);
}
// 获取我们进程数据
ArrayList<String> list = new ArrayList<String>();
for (String a : as) {
if (a.contains("root") && a.contains("进程名")) {
list.add(a);
}
}
/**
* 把数据拆分
*/
ArrayList<String> myPid = new ArrayList<String>();
// 遍历我们进程数据
for (String links : list) {
String ss[] = links.split(" ");
for (String s : ss) {
if (!s.equals("")) {
// 剔除空格
myPid.add(s);
}
}
}
ArrayList<String> killId = new ArrayList<String>();
for (int p = 0; p < myPid.size(); p++) {
if (myPid.get(p).equals("root")) {
killId.add(myPid.get((p + 1)));
}
}
if (killId.size() == 0) {
ToastUtil.tips("服务没在运行");
} else {
Process su = null;
su = Runtime.getRuntime().exec("su ");
os = su.getOutputStream();
ds = new DataOutputStream(os);
int i = 0;
for (String z : killId) {
ds.writeBytes(" kill " + z + "\n");
ds.flush();
i++;
}
states();
if (i == 4) {
ToastUtil.tips("停止成功");
} else {
ToastUtil.tips("停止成功:停止数量:" + i);
}
i = 0;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
is = null;
}
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
}
isr = null;
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
}
br = null;
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
os = null;
}
if (ds != null) {
try {
ds.close();
} catch (IOException e) {
}
ds = null;
}
}
}