生活随笔
收集整理的這篇文章主要介紹了
通过ddmlib杀死某个android进程的方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?首先獲取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)?{??????????????????????????????????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)?{???????????????????????????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();?????????}?????}? 之所以會這么復雜,是因為這個:
???????????
?
轉載于:https://blog.51cto.com/memory/1037994
總結
以上是生活随笔為你收集整理的通过ddmlib杀死某个android进程的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。