android runtime.getruntime()。exec()获取进程ID

问题描述 投票:6回答:4

如何通过Android应用程序使用runtime.getruntime().exec()获取开始的进程的进程ID?

这里是问题。我从我的UI APP使用runtime.getruntime()。exec()启动了一个进程。如果我的Android UI应用仍在运行,则可以使用destroy终止该进程。但是说我使用主页或后退按钮退出应用程序,当我重新打开ui应用程序时,process对象为null。因此,我将需要进程的PID来杀死它。

有更好的方法吗?

android process pid
4个回答
8
投票

Android java.lang.Process实现是java.lang.ProcessManager$ProcessImpl,它具有字段private final int pid;。可以从反射中获得:

public static int getPid(Process p) {
    int pid = -1;

    try {
        Field f = p.getClass().getDeclaredField("pid");
        f.setAccessible(true);
        pid = f.getInt(p);
        f.setAccessible(false);
    } catch (Throwable e) {
        pid = -1;
    }
    return pid;
}

另一种方法-使用toString:

    public String toString() {
        return "Process[pid=" + pid + "]";
    }

您可以解析输出并获得没有反射的pid。

非常完整的方法:

public static int getPid(Process p) {
    int pid = -1;

    try {
        Field f = p.getClass().getDeclaredField("pid");
        f.setAccessible(true);
        pid = f.getInt(p);
        f.setAccessible(false);
    } catch (Throwable ignored) {
        try {
            pid = Integer.parseInt(Pattern.compile("pid=(\\d+)").matcher(p.toString()).group(1));
        } catch (Throwable ignored2) {
            pid = -1;
        }
    }
    return pid;
}

2
投票

您将使用PID终止进程吗?如果是这样,您只需在destroy()实例上调用Process。不需要PID。请注意,您需要使用ProcessBuilder而不是getRuntime().exec()启动该过程,才能正常工作。

如果确实需要进程ID,则可能需要使用Shell脚本。无法从Java AFAIK获取PID。

编辑

由于离开应用程序并返回到应用程序后,您需要在Process上保留一个句柄,所以一种解决方案是在生成Process的类中创建一个静态成员:

private static Process myProcess;

使用此成员存储您从Process上调用start()回来的ProcessBuilder。只要您的应用程序在内存中,静态成员就会一直存在-不必可见。返回您的应用后,应该有可能终止该过程。如果系统碰巧杀死您的应用程序以释放资源,那么您将无法终止子进程(如果该子进程仍在运行),但是该解决方案在大多数情况下都应该有效。


0
投票

[我已经使用ActivityManager进行了类似的操作,尽管在线文档中对此有警告...我也正在作为系统应用程序运行,尽管我不确定这是否重要。

ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
int pid = 0;
List<RunningAppProcessInfo> procInfo = am.getRunningAppProcesses();
for (RunningAppProcessInfo proc : procInfo)
    if (proc.processName.indexOf("myApp") >= 0)
        pid = proc.pid;

-3
投票

请尝试以下操作:int p_Id = android.os.myPid(); For details

© www.soinside.com 2019 - 2024. All rights reserved.