Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After Android 11, how to obtain cpu usage within android application?

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?
like image 245
david Avatar asked Aug 05 '26 20:08

david


2 Answers

Finally, I solve it via

  • executing top -n 1 in android
  • find the entry for my application
  • parse out the cpu usage for my application
    ...
    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;
    }
  • Note you need to replace "com.example.fs" by your application
like image 145
david Avatar answered Aug 07 '26 09:08

david


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.

like image 42
Krokomot Avatar answered Aug 07 '26 10:08

Krokomot