android runtime.getruntime().exec() get process id
android, pid, process
Solution
Android `java.lang.Process` implementation is `java.lang.ProcessManager$ProcessImpl` and it has field `private final int pid;`. It can be get from Reflection:
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;
}
Another way - use toString:
public String toString() {
return "Process[pid=" + pid + "]";
}
You can parse output and get pid without Reflection.
So full method:
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 {
Matcher m = Pattern.compile("pid=(\\d+)").matcher(p.toString());
pid = m.find() ? Integer.parseInt(m.group(1)) : -1;
} catch (Throwable ignored2) {
pid = -1;
}
}
return pid;
}
Problem
How do I get the process id of a process started using `runtime.getruntime().exec()` via an android application?? Here is the problem.. I start a process using runtime.getruntime().exec() from my UI APP. If my android UI app is still running, i can use destroy to kill the process.. But say i exit the app using home or back button and when i reopen the ui app, process object is null. So then i would need the PID of the process to kill it. is there a better way to do this?