0

In order to create an app to detect the current cpu usage on android, I tried fetching the result of the top command using the following simple Kotlin code:

 fun getCPUUsage() {
            val psProc: Process = java.lang.Runtime.getRuntime().exec("top -bn1");
            val read = ByteArray(1024);
            var data = "";
            while (true) {
                val a = psProc.inputStream.read(read);
                if(a <= 0) {
                    break;
                }
                data += String(read, 0, a, Charsets.UTF_8);
                if(psProc.inputStream.available() == 0) {
                    break;
                }
            }
            Log.d("data", data);
        }

However, even running it multiple times, it always returns the same result for the cpu usage (mem slightly differs for each call as expected):

Tasks: 2 total,   1 running,   1 sleeping,   0 stopped,   0 zombie
      Mem: 11791680K total, 10985580K used,   806100K free,   3063808 buffers
     Swap:  4194300K total,  2210372K used,  1983928K free,  2980828K cached
    800%cpu   0%user   0%nice   0%sys 800%idle   0%iow   0%irq   0%sirq   0%host

(Running on a real Octa-Core device with Android 11).

Does my app need a specific permission? Or is this intended "security" behaviour from Android and if so, is there an other way to access the cpu usage under Android 11?

TSGames
  • 679
  • 11
  • 25
  • It's not an exact duplicate, but `/proc/stat` may be what you're looking for. – Martin Zeitler Jan 01 '22 at 14:37
  • /proc/stat seems not accessible at all and since the new Media Storage requirements starting with Android 11 accessing native file system might not be an option either – TSGames Jan 02 '22 at 21:03

0 Answers0