how to get memory usage and cpu usage by application?

后端 未结 4 733
耶瑟儿~
耶瑟儿~ 2021-02-09 16:23

I found this code to get overall cpu usage. is this possible to convert this to tell cpu usage by process? Is there any API by which we can get CPU or Memory usage of android?

4条回答
  •  说谎
    说谎 (楼主)
    2021-02-09 17:12

    Try this:

        private float getCpuPer() { //for single process
    
        float cpuPer = 0;
        try {
            String[] cmd = {"top", "-n", "1"};
            Process process = Runtime.getRuntime().exec(cmd);
            BufferedReader stdInput = new BufferedReader(new
                    InputStreamReader(process.getInputStream()));
    
            BufferedReader stdError = new BufferedReader(new
                    InputStreamReader(process.getErrorStream()));
    
            // read the output from the command
            //System.out.println("Here is the standard output of the command:\n");
            String s = null;
            while ((s = stdInput.readLine()) != null) {
                if (s.contains("your process name")) {
                    String [] arr = s.split(" ");
                    for (int i = 0; i < arr.length; i++) {
                        if (arr[i].contains("%")) {
                            s = arr[i].replace("%", "");
                            cpuPer = Float.parseFloat(s);
                            break;
                        }
                    }
                    //System.out.println(s);
                }
            }
    
            // read any errors from the attempted command
            //System.out.println("Here is the standard error of the command (if any):\n");
            //while ((s = stdError.readLine()) != null) {
                //System.out.println(s);
            //}
        } catch (IOException e) {
            e.printStackTrace();
        }
        return cpuPer;
    }
    

提交回复
热议问题