get Cpu Usage from /proc/stat - Android Hardware

Android examples for Hardware:CPU Information

Description

get Cpu Usage from /proc/stat

Demo Code


//package com.java2s;
import java.io.IOException;
import java.io.RandomAccessFile;

import android.content.Context;

import android.util.Log;

public class Main {
    private static final String TAG = "DeviceUtils";

    public static int getCpuUsage(Context context) {

        try {//www.  ja v a 2  s .  c o  m
            RandomAccessFile reader = new RandomAccessFile("/proc/stat",
                    "r");
            String load = reader.readLine();

            // cpu  127262 1391 77990 17087296 5445 0 1223 0 0 0

            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]);

            Log.d(TAG, "line1 -- " + load);
            Log.d(TAG, "idle1 -- " + idle1);
            Log.d(TAG, "cpu1 -- " + cpu1);

            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]);

            Log.d(TAG, "line2 -- " + load);
            Log.d(TAG, "idle2 -- " + idle2);
            Log.d(TAG, "cpu2 -- " + cpu2);

            Log.d(TAG,
                    "usage -- "
                            + Long.toString((cpu2 - cpu1) * 100
                                    / ((cpu2 + idle2) - (cpu1 + idle1))));

            long usage = cpu2 - cpu1;
            long total = (cpu2 + idle2) - (cpu1 + idle1);

            return (int) (usage * 100 / total);

        } catch (IOException ex) {
            ex.printStackTrace();
            return 0;
        }

    }
}

Related Tutorials