http://vaero.blog.51cto.com/4350852/778139
package com.lenovo.cpuusage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class CPUUsage {
// top命令
public static final String[] CMD = { "top -b -n 1" };
public static final String[] TOP = { "/system/bin/top", "-n", "1" };
public static final String[] TOP_PC = { "top", "-n", "1" };
public static final int count = 0;
public static void main(String[] args) {
String test = run(CMD, "firefox-bin ");
System.out.println(test);
}
// 现在执行top -n 1,我们只需要第二行(用第二行求得CPU占用率,精确数据)
// 第一行:User 35%, System 13%, IOW 0%, IRQ 0% // CPU占用率
// 第二行:User 109 + Nice 0 + Sys 40 + Idle 156 + IOW 0 + IRQ 0 + SIRQ 1 = 306
// // CPU使用情况
public static synchronized String run(String[] cmd) {
String line = "";
InputStream is = null;
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("top -n 1");
is = proc.getInputStream();
// 换成BufferedReader
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
do {
line = buf.readLine();
} while (line != null);
do {
line = buf.readLine();
// 前面有几个空行
if (line.startsWith("User")) {
// 读到第一行时,我们再读取下一行
line = buf.readLine();
break;
}
} while (true);
if (is != null) {
buf.close();
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
// 获取指定应用的top命令获取的信息
// PID CPU% S #THR VSS RSS PCY UID Name // 进程属性
// 如果当前应用不在运行则返回null
public static synchronized String run(String[] cmd, String pkgName) {
String line = null;
InputStream is = null;
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("top -b -n 1");
is = proc.getInputStream();
// 换成BufferedReader
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
do {
line = buf.readLine();
// 读取到相应pkgName跳出循环(或者未找到)
if (null == line || line.endsWith(pkgName)) {
break;
}
} while (true);
if (is != null) {
buf.close();
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
}