[英]android runtime.getruntime().exec() get process id
如何通過 android 應用程序使用runtime.getruntime().exec()
獲取進程的進程 ID?
這是問題所在.. 我從我的 UI APP 中使用 runtime.getruntime().exec() 啟動一個進程。 如果我的 android UI 應用程序仍在運行,我可以使用 destroy 來終止進程.. 但是說我使用主頁或后退按鈕退出應用程序,當我重新打開 ui 應用程序時,進程對象為空。 那么我需要進程的PID來殺死它。
有一個更好的方法嗎?
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 {
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;
}
您會使用 PID 來終止進程嗎? 如果是這樣,您只需在Process
實例上調用destroy()
即可。 不需要PID。 請注意,您需要使用ProcessBuilder
而不是getRuntime().exec()
來啟動進程,才能使其工作。
如果確實需要進程 ID,則可能需要使用 shell 腳本。 AFAIK 無法從 Java 獲取 PID。
編輯:
由於您需要在離開應用程序並返回后保留對Process
的句柄,因此一種解決方案是在生成Process
的類中創建一個靜態成員:
private static Process myProcess;
使用此成員來存儲您通過在ProcessBuilder
上調用start()
返回的Process
。 只要您的應用程序在內存中,靜態成員就會一直存在——它不一定是可見的。 返回您的應用程序后應該可以終止該進程。 如果系統碰巧殺死您的應用程序以釋放資源,那么您將無法終止子進程(如果它保持運行),但此解決方案應該適用於大多數情況。
我已經使用 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;
嘗試以下操作:
int p_Id = android.os.myPid(); 詳情
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.