獲取APP相關(guān)Cpu占用率和內(nèi)存情況

獲取設(shè)備應(yīng)用運(yùn)行的狀態(tài)信息


    /**
     * 獲取手機(jī)信息
     */
    public void getPhoneInfo() throws IOException {

        TelephonyManager tm = (TelephonyManager) 
        String mtyb = android.os.Build.BRAND;// 手機(jī)品牌
        String mtype = android.os.Build.MODEL; // 手機(jī)型號(hào)

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

        mTextView.append("當(dāng)前可用內(nèi)存/總內(nèi)存: " + getAvailMemory() + "\n");

        mTextView.append("進(jìn)程內(nèi)存/上限: " + 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當(dāng)前頻率: " + getCurCpuFreq() + "\n");
        mTextView.append("CPU info: " + Long.toString(getTotolCpuInfo()) + "\n");
        mTextView.append("線程: " + "\n" + getAllThread() + "\n");
        mTextView.append("線程: " + "\n" + printThread() + "\n");
    }

1. 獲取當(dāng)前可用內(nèi)存大小

     /**
     * 獲取當(dāng)前可用內(nèi)存大小/總內(nèi)存(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);
    }



    //進(jìn)程內(nèi)存上限
    private int getMemoryMax() {
        return (int) (Runtime.getRuntime().maxMemory()/1024/1024);
    }

    //進(jìn)程總內(nèi)存
    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;

    }

/*
* 計(jì)算某個(gè)時(shí)間段內(nèi)AppCpuTime與TotalCpuTime的變化,然后按照比例換算成該應(yīng)用的Cpu使用率。

* Android系統(tǒng)本省也有一個(gè)類是用來(lái)顯示Cpu使用率的:

* android/system/frameworks/base/packages/SystemUI/src/com/android/systemui/LoadAverageService.java
* 閱讀源碼發(fā)現(xiàn)也是讀取/proc目錄下的文件來(lái)計(jì)算Cpu使用率
    * */
    public static float getProcessCpuRate()
    {

        float totalCpuTime1 = getTotalCpuTime();
        float processCpuTime1 = getAppCpuTime();
        try
        {
            Thread.sleep(20);//360太大會(huì)卡頓UI

        }
        catch (Exception e)
        {
        }

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

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

        return cpuRate;
    }

    //獲取某進(jìn)程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";
    }

    // 實(shí)時(shí)獲取CPU當(dāng)前頻率(單位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("線程號(hào):" + i + " = " + lstThreads[i].getName());
  
                threadStr += " 線程號(hào):" + 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;
    }


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容