android系统信息,cpu、内存、电池等

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;
	}
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值