首页 > 解决方案 > 如何以编程方式获取 Linux 应用程序组名称?

问题描述

如何以编程方式获取 Linux 应用程序组名称?

没有直接的方法可以使用 SDK 获取它。

标签: android

解决方案


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();

}

推荐阅读