Android中查看CPU和内存

Android系统使用的是linux内核,那么我们可以在程序中去调用cat /proc/meminfo和cat /proc/cpuino来查看内存和CPU的情况,下面是程序:

public class CpuSpeed extends Activity {
	/** Called when the activity is first created. */

	private TextView cpuInfo;
	private TextView memoryInfo;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		cpuInfo = (TextView) findViewById(R.id.cpuinfo);
		cpuInfo.setText(getCPUinfo());
		memoryInfo = (TextView) findViewById(R.id.memoryinfo);
		memoryInfo.setText(getMemoryInfo());

	}

	private String getMemoryInfo() {
		ProcessBuilder cmd;
		String result = new String();

		try {
			String[] args = { "/system/bin/cat", "/proc/meminfo" };
			cmd = new ProcessBuilder(args);

			Process process = cmd.start();
			InputStream in = process.getInputStream();
			byte[] re = new byte[1024];
			while (in.read(re) != -1) {
				System.out.println(new String(re));
				result = result + new String(re);

			}
			in.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return result;

	}

	private String getCPUinfo() {
		ProcessBuilder cmd;
		String result = "";

		try {
			String[] args = { "/system/bin/cat", "/proc/cpuinfo" };
			cmd = new ProcessBuilder(args);

			Process process = cmd.start();
			InputStream in = process.getInputStream();
			byte[] re = new byte[1024];
			while (in.read(re) != -1) {
				System.out.println(new String(re));
				result = result + new String(re);
			}
			in.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return result;
	}

}

其实核心无非就是ProcessBuilder的运用,去启动命令行去读操作系统。

String[] args = {"/system/bin/cat", "/proc/cpuinfo"};
cmd = new ProcessBuilder(args);

Process process = cmd.start();
InputStream in = process.getInputStream();

然后再IO输入流读入就可以了。

暂无评论
  • 1:请一针见血的评论。
  • 2:评论需要审核通过后才能显示。
  • 3:评论字数限制在1000字以内。
  • 当前字数:0
热门文章
推荐文章
随机文章
关于本站 - 广告服务 - 版权声明 - 联系我们 - 友情链接 - 网站地图 - 帮助中心