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

时间:2018-06-22 14:21:18

标签: android

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

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

1 个答案:

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

}