android - 如何以编程方式获取 Linux 应用程序组名称?
问题描述
如何以编程方式获取 Linux 应用程序组名称?
没有直接的方法可以使用 SDK 获取它。
解决方案
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();
}
推荐阅读
- c# - 如何将 doctype 解析为字符串作为 html doctype
- ionic3 - 如何将视频放在 div 上并且适用于设备 android
- android - Android pie非sdk接口问题
- mysql - 为学生分配多个科目
- android - App Gradle,如何在使用 Firebase 核心时修复错误?
- python - 使用具有各种功能的字典过滤熊猫数据框
- answer-set-programming - ASP 中如何将否定理解为失败?
- swift - CoreML 无法验证输入
- google-chrome - (Win10上的Chrome)为什么在创建页面快捷方式时“打开为窗口”复选框消失了
- c# - 单击按钮时 DataGridTextColumn 显示 NaN