Obtain CPU usage,example 0.5. - Android Hardware

Android examples for Hardware:CPU Usage

Description

Obtain CPU usage,example 0.5.

Demo Code

import java.io.BufferedReader;
import java.io.InputStreamReader;

import android.text.TextUtils;

public class Main {
  /**/*  w  w w . j  a  v  a 2 s . c  o m*/
   * Obtain CPU usage,example 0.5.
   * 
   * @return
   */
  public static final float obtainCUPUsage() {
    int totalUsage = 0;
    try {
      java.lang.Process p = Runtime.getRuntime().exec("top -m 15 -d 1 -n 1");
      BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line = reader.readLine();
      while (line != null) {
        if (!TextUtils.isEmpty(line)) {
          break;
        }
        line = reader.readLine();
      }
      if (!TextUtils.isEmpty(line)) {
        String[] items = line.split(",");
        if (null != items && items.length > 0) {
          for (String item : items) {
            if (!TextUtils.isEmpty(item)) {
              item = item.trim();
              String usage = item.split(" ")[1];
              usage = usage.substring(0, usage.length() - 1);
              int rate = Integer.valueOf(usage);
              totalUsage += rate;
            }
          }
        }
      }
      p.waitFor();
    } catch (Exception e) {
      LogUtility.d(e);
    }
    return totalUsage / 100f;
  }
}

Related Tutorials