0

I need to get the CPU usage percentage (load) and its temperature, like the CPU-Z app does. Please I need help. reference.

I have this code but I don't know how it works to know the total percentage of CPU usage no matter how many cores it has

public static float getCpuUsage() {
    try {
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        String load = reader.readLine();

        String[] toks = load.split(" ");

        long idle1 = Long.parseLong(toks[5]);
        long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                + 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[5]);
        long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                + 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;
}
  • 1
    Where's your code? What have you done to solve your own problem? Have you searched for similar questions on Stack Overflow? Have you read about [how to ask](https://stackoverflow.com/help/how-to-ask) questions on this site? – MarsAtomic Mar 24 '20 at 15:56
  • Does this answer your question? [How I get CPU usage and temperature information into an android app?](https://stackoverflow.com/questions/34808216/how-i-get-cpu-usage-and-temperature-information-into-an-android-app) – Gewure Mar 24 '20 at 16:02
  • 1
    Does this answer your question? [How get average CPU usage in Android?](https://stackoverflow.com/questions/23261306/how-get-average-cpu-usage-in-android) – Aznhar Mar 24 '20 at 16:07

0 Answers0