DDMS
里有个Cause GC
命令,用来要求虚拟机强制GC
,如下图:
但是在有些环境下面,测试同学,或者用户机器上面没有安装Android Sdk
,这个时候使用adb shell
来执行GC
命令是比较合适的,但是网上搜索了一下,发现adb shell
下没有提供这个命令。
根据网上介绍,执行GC
命令实际上是通过kill
命令向进程发送了数字为10
的自定义信号而已,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
private void gc() { String pid = String.valueOf(ProcessUtils .getProcessPID(AUTManager.pkn.toString())); if (!pid.equals("-1")) { boolean isSucess = true; ProcessBuilder pb = null; String cmd = "kill -10 " + pid; pb = new ProcessBuilder("su", "-c", cmd); Process exec = null; pb.redirectErrorStream(true); try { exec = pb.start(); InputStream is = exec.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(is)); while ((reader.readLine()) != null) { isSucess = false; } } catch (Exception e) { e.printStackTrace(); isSucess = false; } // 至此命令算是执行成功 if (isSucess) { handler.sendEmptyMessage(5); } } else { Log.d("gc error", "pid not found!"); } } private void dumpHeap() { String pid = String.valueOf(ProcessUtils .getProcessPID(AUTManager.pkn.toString())); if (!pid.equals("-1")) { boolean isSucess = true; ProcessBuilder pb = null; String sFolder = Env.S_ROOT_DUMP_FOLDER + AUTManager.pkn.toString() + "/"; File folder = new File(sFolder); if (!folder.exists()) { folder.mkdirs(); } String cmd = "am dumpheap " + pid + " "// 命令 + Env.S_ROOT_DUMP_FOLDER + AUTManager.pkn.toString() + "/"// 输出路径 + "dump_" + pid + "_" + GTUtils.getSaveDate() + ".hprof"; // 输出文件名 pb = new ProcessBuilder("su", "-c", cmd); Process exec = null; pb.redirectErrorStream(true); try { exec = pb.start(); InputStream is = exec.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(is)); while ((reader.readLine()) != null) { isSucess = false; } } catch (Exception e) { e.printStackTrace(); isSucess = false; } // 至此命令算是执行成功 if (isSucess) { handler.sendEmptyMessage(6); } } else { Log.d("dump error", "pid not found!"); } } |
相同道理,我们只要直接在adb shell
里面直接向进程发送数字为10
的自定义信号就可以了。