从所有正在运行的应用程序获得PID(Android)
问题描述:
我正在创建一个Android应用程序,该应用程序应能够访问设备上运行的其他应用程序(如Google Maps,计算器等)的PID。我每秒都会运行以下代码,以便在Android设备上运行正在运行的进程。但是,当我运行它时,它只显示我的应用程序信息,即使其他3个应用程序也在运行。有没有人有关于如何获得在Android设备上运行的其他应用程序的PID的任何建议?从所有正在运行的应用程序获得PID(Android)
try {
Process process = Runtime.getRuntime().exec("ps");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
while(true) {
String line = in.readLine();
System.out.println(line);
if (line == null) break;
}
}
catch (IOException e) {
e.printStackTrace();
}
答
可以使用活动管理
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> pids = am.getRunningAppProcesses();
int processid = 0;
for (int i = 0; i < pids.size(); i++) {
ActivityManager.RunningAppProcessInfo info = pids.get(i);
System.out.println(info.pid);
}
尝试 'PS -A' 得到它。这在我的本地列出了更多的流程 – vdelricco