android 通过linux命令来停止某个进程

项目中要用 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;
			}
		}
	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值