public static float getProcessCpuRate() { float totalCpuTime1 = getTotalCpuTime(); float processCpuTime1 = getAppCpuTime(); try { Thread.sleep(360); } catch (Exception e) { } float totalCpuTime2 = getTotalCpuTime(); float processCpuTime2 = getAppCpuTime(); float cpuRate = 100 * (processCpuTime2 - processCpuTime1) / (totalCpuTime2 - totalCpuTime1); return cpuRate; } public static long getTotalCpuTime() { // 獲取系統總CPU使用時間 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) { ex.printStackTrace(); } long 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]); return totalCpu; } public static long getAppCpuTime() { // 獲取應用佔用的CPU時間 String[] cpuInfos = null; try { int pid = android.os.Process.myPid(); BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream("/proc/" + pid + "/stat")), 1000); String load = reader.readLine(); reader.close(); cpuInfos = load.split(" "); } catch (IOException ex) { ex.printStackTrace(); } long appCpuTime = Long.parseLong(cpuInfos[13]) + Long.parseLong(cpuInfos[14]) + Long.parseLong(cpuInfos[15]) + Long.parseLong(cpuInfos[16]); return appCpuTime; } |
計算某個時間段內AppCpuTime與TotalCpuTime的變化,而後按照比例換算成該應用的Cpu使用率。java
Android系統本省也有一個類是用來顯示Cpu使用率的:android
android/system/frameworks/base/packages/SystemUI/src/com/android/systemui/LoadAverageService.java
閱讀源碼發現也是讀取/proc目錄下的文件來計算Cpu使用率
另一種方式Runtime.getRuntime().exec("top -d 1 -n 1"),可是每次都獲取到的cpu使用率爲0,找不到緣由http://www.m2catalyst.com/tutorial-finding-cpu-usage-for-individual-android-apps/app