Runtime.exec()抛出工作目录:null环境:null

时间:2015-09-08 21:51:11

标签: java process adb android-uiautomator

运行exec()时出错。命令:

set `ps | grep <package name>`

工作目录:null环境:null

我正在运行以下命令来获取我的应用程序的进程ID

private int getProcessId(String packageName) {
    int processid = -1;
    try {
        runADBCommand(new String[] {"set `ps | grep " + packageName + "`"});
        processid = Integer.parseInt(runADBCommand(new String[]{"print $2"}));
    } catch (IOException e) {
        e.printStackTrace();
        Log.e(LOG_TAG, e.getMessage());
    }
    Log.w(LOG_TAG, "Process id: " + processid);
    return processid;
}

runADBCommand函数如下所示:

private String runADBCommand(String[] adbCommand) throws IOException {
    String returnValue = "", line;
    InputStream inStream = null;
    try {
        Process process = Runtime.getRuntime().exec(adbCommand);
        inStream = process.getInputStream();
        BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(inStream));
        while ((line = brCleanUp.readLine()) != null) {
            returnValue = returnValue + line + "\n";
        }
        brCleanUp.close();
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            Log.e(LOG_TAG, e.getMessage());
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(LOG_TAG, e.getMessage());
    }
    return returnValue;
}

我试图在非root的Moto G设备上运行这个并且也切,awk不是 在设备shell中可以直接获取pid。

2 个答案:

答案 0 :(得分:0)

您正在运行set命令,这是一个shell命令,但您没有运行shell。所以它可能无法奏效。您需要在其前面添加sh -c。但我不明白这一点。当shell退出时,set的结果将丢失。它没有意义。

答案 1 :(得分:-1)

不知怎的,我发现set命令在非root设备上不起作用,并且moto G没有awk或cut作为默认命令,所以我尝试了不同的方法,而不是直接从adb shell获取PID。

private int getProcessId() {
    try {
        String process = runADBCommand("ps <<last 15 characters of packagename>>");
        return Integer.parseInt(process.split("\n")[1].trim().split(" ")[3]);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return -1;
}

此功能完美地给出了结果。

另外如果您注意到我现在没有将数组作为命令发送,而只是发送一个字符串,则runADBCommand与此相同,唯一的区别是它接受字符串而不是字符串数组。