获取APP相关Cpu占用率和内存情况

获取设备应用运行的状态信息


    /**
     * 获取手机信息
     */
    public void getPhoneInfo() throws IOException {

        TelephonyManager tm = (TelephonyManager) 
        String mtyb = android.os.Build.BRAND;// 手机品牌
        String mtype = android.os.Build.MODEL; // 手机型号

        mTextView.setText("品牌: " + mtyb + "\n" + "型号: " + mtype + "\n" + "版本: Android "
                + android.os.Build.VERSION.RELEASE + "\n" );

        mTextView.append("当前可用内存/总内存: " + getAvailMemory() + "\n");

        mTextView.append("进程内存/上限: " + getPidMemorySize(android.os.Process.myPid(), getApplicationContext()) + "MB/" + + getMemoryMax() + "MB\n");
        mTextView.append("CPU名字: " + getCpuName() + "\n");
        mTextView.append("CPU利用率:" + getProcessCpuRate() + "%\n");
        mTextView.append("CPU最大频率: " + getMaxCpuFreq() + "\n");
        mTextView.append("CPU最小频率: " + getMinCpuFreq() + "\n");
        mTextView.append("CPU当前频率: " + getCurCpuFreq() + "\n");
        mTextView.append("CPU info: " + Long.toString(getTotolCpuInfo()) + "\n");
        mTextView.append("线程: " + "\n" + getAllThread() + "\n");
        mTextView.append("线程: " + "\n" + printThread() + "\n");
    }

1. 获取当前可用内存大小

     /**
     * 获取当前可用内存大小/总内存(MB)
     *
     * @return
     */
    private String getAvailMemory() {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return Formatter.formatFileSize(getBaseContext(), mi.availMem) + "/" + Formatter.formatFileSize(getBaseContext(), mi.totalMem);
    }



    //进程内存上限
    private int getMemoryMax() {
        return (int) (Runtime.getRuntime().maxMemory()/1024/1024);
    }

    //进程总内存
    public static int getPidMemorySize(int pid, Context context) {

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        int[] myMempid = new int[] { pid };
        Debug.MemoryInfo[] memoryInfo = am.getProcessMemoryInfo(myMempid);
        int memSize = memoryInfo[0].getTotalPss();
     
        return memSize/1024;
    }

2. 获取CPU占用率的方法

//获取cpu名字
     public static String getCpuName() {
        try {
            FileReader fr = new FileReader("/proc/cpuinfo");
            BufferedReader br = new BufferedReader(fr);
            String text = br.readLine();
            String[] array = text.split(":\\s+", 2);
            for (int i = 0; i < array.length; i++) {
            }
            return array[1];
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    public static long getTotolCpuInfo(){
        String[] cpuInfos = null;
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream("/proc/stat")), 1000);
            String load = reader.readLine();
            reader.close();
            cpuInfos = load.split(" ");
        }catch(IOException ex){
            Log.e(TAG, "IOException" + ex.toString());
            return 0;
        }
        long totalCpu = 0;
        try{
            totalCpu = Long.parseLong(cpuInfos[2])
                    + Long.parseLong(cpuInfos[3]) + Long.parseLong(cpuInfos[4])
                    + Long.parseLong(cpuInfos[6]) + Long.parseLong(cpuInfos[5])
                    + Long.parseLong(cpuInfos[7]) + Long.parseLong(cpuInfos[8]);
        }catch(ArrayIndexOutOfBoundsException e){
            Log.i(TAG, "ArrayIndexOutOfBoundsException" + e.toString());
            return 0;
        }

        return totalCpu;

    }

/*
* 计算某个时间段内AppCpuTime与TotalCpuTime的变化,然后按照比例换算成该应用的Cpu使用率。

* Android系统本省也有一个类是用来显示Cpu使用率的:

* android/system/frameworks/base/packages/SystemUI/src/com/android/systemui/LoadAverageService.java
* 阅读源码发现也是读取/proc目录下的文件来计算Cpu使用率
    * */
    public static float getProcessCpuRate()
    {

        float totalCpuTime1 = getTotalCpuTime();
        float processCpuTime1 = getAppCpuTime();
        try
        {
            Thread.sleep(20);//360太大会卡顿UI

        }
        catch (Exception e)
        {
        }

        float totalCpuTime2 = getTotalCpuTime();
        float processCpuTime2 = getAppCpuTime();

        float cpuRate = 100 * (processCpuTime2 - processCpuTime1)
                / (totalCpuTime2 - totalCpuTime1);

        return cpuRate;
    }

    //获取某进程CPU占用率的方法
    public static double getProcessCpuUsage(String pid) {
        try {
            RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
            String load = reader.readLine();
            String[] toks = load.split(" ");

            double totalCpuTime1 = 0.0;
            int len = toks.length;
            for (int i = 2; i < len; i ++) {
                totalCpuTime1 += Double.parseDouble(toks[i]);
            }


            BufferedReader readerBB = new BufferedReader(new FileReader("/proc/"));
            String processNameB = readerBB.readLine();
            RandomAccessFile reader2 = new RandomAccessFile("/proc/"+ pid +"/stat", "r");
            String load2 = reader2.readLine();
            String[] toks2 = load2.split(" ");

            double processCpuTime1 = 0.0;
            double utime = Double.parseDouble(toks2[13]);
            double stime = Double.parseDouble(toks2[14]);
            double cutime = Double.parseDouble(toks2[15]);
            double cstime = Double.parseDouble(toks2[16]);

            processCpuTime1 = utime + stime + cutime + cstime;

            try {
                Thread.sleep(360);
            } catch (Exception e) {
                e.printStackTrace();
            }
            reader.seek(0);
            load = reader.readLine();
            reader.close();
            toks = load.split(" ");
            double totalCpuTime2 = 0.0;
            len = toks.length;
            for (int i = 2; i < len; i ++) {
                totalCpuTime2 += Double.parseDouble(toks[i]);
            }
            reader2.seek(0);
            load2 = reader2.readLine();
            String []toks3 = load2.split(" ");

            double processCpuTime2 = 0.0;
            utime = Double.parseDouble(toks3[13]);
            stime = Double.parseDouble(toks3[14]);
            cutime = Double.parseDouble(toks3[15]);
            cstime = Double.parseDouble(toks3[16]);

            processCpuTime2 = utime + stime + cutime + cstime;
            double usage = (processCpuTime2 - processCpuTime1) * 100.00
                    / ( totalCpuTime2 - totalCpuTime1);
            BigDecimal b = new BigDecimal(usage);
            double res = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            return res;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return 0.0;
    }

    public static String getMaxCpuFreq() {
        String result = "";
        ProcessBuilder cmd;
        try {
            String[] args = {"/system/bin/cat",
                    "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"};
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            InputStream in = process.getInputStream();
            byte[] re = new byte[24];
            while (in.read(re) != -1) {
                result = result + new String(re);
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = "N/A";
        }
        return result.trim() + "Hz";
    }

    // 获取CPU最小频率(单位KHZ)

    public static String getMinCpuFreq() {
        String result = "";
        ProcessBuilder cmd;
        try {
            String[] args = {"/system/bin/cat",
                    "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq"};
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            InputStream in = process.getInputStream();
            byte[] re = new byte[24];
            while (in.read(re) != -1) {
                result = result + new String(re);
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = "N/A";
        }
        return result.trim() + "Hz";
    }

    // 实时获取CPU当前频率(单位KHZ)

    public static String getCurCpuFreq() {
        String result = "N/A";
        try {
            FileReader fr = new FileReader(
                    "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
            BufferedReader br = new BufferedReader(fr);
            String text = br.readLine();
            result = text.trim() + "Hz";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

3. 获取线程名字

//方法一
    private String getAllThread(){
        String threadStr = "";
        ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();

        int noThreads = currentGroup.activeCount();

        Thread[] lstThreads = new Thread[noThreads];

        currentGroup.enumerate(lstThreads);

        for (int i = 0; i < noThreads; i++) {

            System.out.println("线程号:" + i + " = " + lstThreads[i].getName());
  
                threadStr += " 线程号:" + i + " = " + lstThreads[i].getName() ;
                threadStr += " id=" + lstThreads[i].getId() ;
                threadStr += " cpuuse=" +  Double.toString(getProcessCpuUsage(Long.toString(lstThreads[i].getId())));
//                threadStr += "--" + getPidMemorySize((int) lstThreads[i].getId(), getApplicationContext());
                threadStr += "\n";
            
        }

        return threadStr;
    }
//方法二
    private String printThread() {

        String threadStr = "";
        Map<Thread, StackTraceElement[]> stacks = Thread.getAllStackTraces();
        Set<Thread> set = stacks.keySet();
        for (Thread key : set) {
            StackTraceElement[] stackTraceElements = stacks.get(key);

            threadStr += " 线程 : " + key.getName() ;
            threadStr += " id=" + key.getId() ;
            threadStr += " cpuuse=" +  Double.toString(getProcessCpuUsage(Long.toString(key.getId())));
            threadStr += "\n";

            Log.d(TAG, "---- print thread: " + key.getName() + " start ----");
            for (StackTraceElement st : stackTraceElements) {
                Log.d(TAG, " StackTraceElement: " + st.toString());
            }
            Log.d(TAG, "---- print thread: " + key.getName() + " end ----");
        }
        return threadStr;
    }


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容