是否有任何API可以让我们获得android的CPU或内存使用情况?
我尝试过如下代码:
package com.infostretch.mainactivity;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class CPULoad
{
long total = 0;
long idle = 0;
float usage = 0;
public CPULoad()
{
readUsage();
}
public float getUsage()
{
readUsage();
return usage;
}
private void readUsage()
{
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("/proc/stat")), 1000);
String load = reader.readLine();
reader.close();
String[] toks = load.split(" ");
long currTotal = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]);
long currIdle = Long.parseLong(toks[5]);
this.usage = (currTotal - total) * 100.0f / (currTotal - total + currIdle - idle);
this.total = currTotal;
this.idle = currIdle;
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
这是正确的做法吗?
最佳答案
我使用这个函数来计算 CPU 使用率。希望对你有帮助。
private float readUsage() {
try {
RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
String load = reader.readLine();
String[] toks = load.split(" +"); // Split on one or more spaces
long idle1 = Long.parseLong(toks[4]);
long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
try {
Thread.sleep(360);
} catch (Exception e) {}
reader.seek(0);
load = reader.readLine();
reader.close();
toks = load.split(" +");
long idle2 = Long.parseLong(toks[4]);
long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));
} catch (IOException ex) {
ex.printStackTrace();
}
return 0;
}
关于android - 在 Android 中获取内存使用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3118234/