如何以编程方式获取Linux应用程序组名称?
没有直接使用SDK来获取它的方法。
答案 0 :(得分:0)
public static String getGroupName(Context context) {
String groupName = null;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
for (String activeProcess : processInfo.pkgList) {
try {
if (activeProcess.compareTo(context.getPackageName()) == 0) {
Process process = Runtime.getRuntime().exec("ps -p " + processInfo.pid);
String psOutput = streamToString(process.getInputStream());
String[] lines = psOutput.split("\n");
String valueLine = lines[1];
int firstSpace = valueLine.indexOf(" ", 0);
groupName = valueLine.substring(0, firstSpace);
}
}
catch (IOException ioe){
Log.e(TAG, "Error while getting group name", ioe);
}
catch (RuntimeException rte){
Log.e(TAG, "Error while getting group name", rte);
}
}
}
return groupName;
}
private static String streamToString(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
Log.e(TAG, "Error while reading stream", e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
Log.e(TAG, "Error while closing stream", e);
}
}
}
return sb.toString();
}