app的cpu使用率
6.0以前(應(yīng)該包含6.0,未測(cè)試)可以通過查看/proc/stat文件里面的內(nèi)容然后通過計(jì)算得出,步驟如下
adb shell
ls
cd proc
ls
cat stat
就可以看到實(shí)時(shí)記錄的數(shù)據(jù)。
但是7.0開始,這個(gè)/proc/stat不再對(duì)app開放,除非root,否則會(huì)報(bào)Permission denied的日志。雖然在cmd能打印,但是代碼中讀取到的是空數(shù)據(jù)。
top 指令
top -n 1
(第二個(gè)參數(shù)是數(shù)字一,不是L)
這樣就能獲取到cpu的數(shù)據(jù)。但是顯示會(huì)有問題,測(cè)試每種手機(jī)的cpu數(shù)據(jù)列都不一樣,很難定位截取,但是有規(guī)律,所有手機(jī)都是以PID為起始列,然后有些手機(jī)CPU的列會(huì)和其他列連在一起,又但是只要連在一起的,會(huì)用中括號(hào)區(qū)別。只要有規(guī)律,就可以用代碼表示:
public static void execShellGetCpuData(String packageName) {
Process process = null;
DataOutputStream os = null;
BufferedReader in = null;
try {
process = Runtime.getRuntime().exec("sh");
os = new DataOutputStream(process.getOutputStream());
in = new BufferedReader(new InputStreamReader(process.getInputStream()));
os.writeBytes("top -n 1\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
String line = null;
int index = -1;
while ((line = in.readLine()) != null) {
Log.d("===>", String.format("原始=%s", line));
if (line.contains("PID") && line.contains("CPU")) {
String[] split = line.split("( )+");
int length = split.length;
boolean skip = true;
for (int i = 0; i < length; i++) {
Log.d("===>", String.format("當(dāng)前列%s", split[i]));
if (skip && !"PID".equals(split[i])) {
skip = false;
continue;
}
index++;
if (split[i].contains("CPU")) {
if (split[i].contains("[")) {
index++;
}
break;
}
}
} else {
//說明找到了
if (index != -1 && line.contains(packageName)) {
String[] titles = line.trim().split("( )+");
int length = titles.length;
for (int i = 0; i < length; i++) {
if (i == index) {
Log.d("===>", String.format("index=%s, cpu=%s", index, titles[i].replace("%", "")));
}
}
break;
}
}
}
process.waitFor();
} catch (Exception e) {
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
}
}
}