/proc/stat, andHardwarePropertiesManager cannot be used in normal application for the permission "android.permission.DEVICE_POWER" is only granted to system apps.Finally, I solve it via
top -n 1 in android ...
private double sampleCPU() {
int rate = 0;
try {
String Result;
Process p = Runtime.getRuntime().exec("top -n 1");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((Result = br.readLine()) !=null){
// replace "com.example.fs" by your application
if (Result.contains("com.example.fs")) {
String[] info = Result.trim().replaceAll(" +"," ").split(" ");
return Double.valueOf(info[9]);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return rate;
}
In general you might be interested in the Android Dev Docs' System Tracing Guides.
In particular take a look at this Stack Overflow Post (incl. sample code, start reading after "Edit") on a similar question.
Basically this approach uses the CPU frequency as the basis for determining the CPU usage. For that the number n of CPU cores is determined and then the corresponding frequencies are read from "/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq", where 0 <= i < n.
That's also the same approach which has been used in the corresponding source file of the apps CPU Info (that link has also been provided in a comment by muetzenflo) and CPU Stats.
Note, that using the CpuStatsCollector API as sometimes suggested, can not be recommended, as that API is not public, and therefore lacks documentation and so will sooner or later lead you into problems and code rewriting. Use at your own risk. That's in my opinion also the problem with shirsh shukla's answer. It might work, but it employs a non-public API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With