Target
- I want to monitor the CPU usage for my APP (global CPU usage is also okay for me) within android application.
Background
- After Android 11, the normal application cannot access to
/proc/stat
, and HardwarePropertiesManager
cannot be used in normal application for the permission"android.permission.DEVICE_POWER"
is only granted to system apps.- All the solutions that I can obtain in google are the same with the above two methods.
Question
- So is there any way that I can obtain CPU usage within an android application after Android 11?
3
Answers
Finally, I solve it via
top -n 1
in androidbasically In an Android application after Android 11, it uses the CpuMetricCollector class of the Google Play Games Services SDK to determine CPU usage.
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"
, where0 <= 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.