Androidのjava.lang.Process
実装はjava.lang.ProcessManager$ProcessImpl
、 field を持っていますprivate final int pid;
。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;
}
別の方法 - 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 {
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;
}