通过ddmlib杀死某个android进程的方法
16lz
2021-01-23
首先获取ps指令的打印信息:
- private static String getPsPrint(IDevice device) {
- OutputStream os = new ByteArrayOutputStream();
- try {
- device.executeShellCommand("ps",
- new OutputStreamShellOutputReceiver(os));
- os.flush();
- return os.toString();
- } catch (TimeoutException e) {
- e.printStackTrace();
- } catch (AdbCommandRejectedException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ShellCommandUnresponsiveException e) {
- e.printStackTrace();
- }
- return "";
- }
其中OutputStreamShellOutputReceiver类:
- public class OutputStreamShellOutputReceiver implements IShellOutputReceiver {
- OutputStream os;
- public OutputStreamShellOutputReceiver(OutputStream os) {
- this.os = os;
- }
- public boolean isCancelled() {
- return false;
- }
- public void flush() {
- }
- public void addOutput(byte[] buf, int off, int len) {
- try {
- os.write(buf,off,len);
- } catch(IOException ex) {
- throw new RuntimeException(ex);
- }
- }
- }
获得ps的打印信息之后,需要根据进程名分析出pid:
- public static String parsePid(IDevice device, String exeName) {
- String content = getPsPrint(device);
- String[] pidInfos = content.split("\n");
- for (String info : pidInfos) {
- if (info != null) {
- // shell 18867 18856 852 300 c022c0bc afe0cdec S ./gsnap
- if (info.contains(exeName)) {
- String[] fragments = info.split(" ");
- int idx = 0;
- for (String str : fragments) {
- if ((str != null) && (!str.trim().equals(""))) {
- idx++;
- }
- if (idx == 2) {
- return str;
- }
- }
- }
- }
- }
- return "";
- }
最后,根据得到的pid,杀掉此android进程:
- public static void killProcess(IDevice device, String pid) {
- // 旧的手机,缺乏grep和awk程序!
- //String killCmd = "kill -9 `ps | grep \"gsnap\" | grep -v \"grep\" | awk '{print $2}'`";
- String killCmd = "kill -9 " + pid;
- try {
- device.executeShellCommand(killCmd,
- new OutputStreamShellOutputReceiver(System.out));
- } catch (TimeoutException e) {
- e.printStackTrace();
- } catch (AdbCommandRejectedException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ShellCommandUnresponsiveException e) {
- e.printStackTrace();
- }
- }
之所以会这么复杂,是因为这个:
- // 旧的手机,缺乏grep和awk程序!
- //String killCmd = "kill -9 `ps | grep \"gsnap\" | grep -v \"grep\" | awk '{print $2}'`";
更多相关文章
- Android入门:HTML布局中Android程序与JAVASCRIPT的交互
- Android 获取手机网络状态
- Android检测手机是否插入/连接耳机
- android 启动应用程序
- 1.1使用内置的Camara应用程序捕捉图像
- Android通过包名打开手机应用商城寻找所指定App
- Android中调用locationManager.getProvider(LocationManager.GPS
- Android 获取imei号码,获取手机型号和系统版本号