獲取單個進程cpu使用效率

//獲取單個進程的CPU使用率
double procCpu = Tool.getProcCpu(Process.myPid());

public class Tool {
public static boolean isExsit() {
File file = new File(Environment.getExternalStorageDirectory(),
“docomlayout.txt”);
if (file.exists()) {
return true;
}
return false;
}

/**
 * 讀取閘機主界面文件
 *
 * @return
 */
public static String readFile() {
    StringBuffer sb = new StringBuffer();
    try {
        File file = new File(Environment.getExternalStorageDirectory(),
                "docomlayout.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String readline = "";

        while ((readline = br.readLine()) != null) {
            System.out.println("readline:" + readline);
            sb.append(readline);
        }
        br.close();
        System.out.println("讀取成功:" + sb.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

/**
 * 讀取閘機副屏界面
 *
 * @return
 */
public static String readFile1() {
    StringBuffer sb = new StringBuffer();
    try {
        File file = new File(Environment.getExternalStorageDirectory(),
                "docomlayout1.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String readline = "";

        while ((readline = br.readLine()) != null) {
            System.out.println("readline:" + readline);
            sb.append(readline);
        }
        br.close();
        System.out.println("讀取成功:" + sb.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

/**
 * 寫入閘機主界面
 *
 * @param s
 */
public static void writeFile(String s) {
    try {
        File file = new File(Environment.getExternalStorageDirectory(),
                "docomlayout.txt");
        //第二個參數意義是說是否以append方式添加內容
        Writer writer = new BufferedWriter(
                new OutputStreamWriter(
                        new FileOutputStream(file, false), "UTF-8"));
        String info = s;
        writer.write(info);
        writer.flush();
        System.out.println("寫入成功");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * 寫入閘機副屏界面
 *
 * @param s
 */
public static void writeFile1(String s) {
    try {
        File file = new File(Environment.getExternalStorageDirectory(),
                "docomlayout1.txt");
        //第二個參數意義是說是否以append方式添加內容
        Writer writer = new BufferedWriter(
                new OutputStreamWriter(
                        new FileOutputStream(file, false), "UTF-8"));
        String info = s;
        writer.write(info);
        writer.flush();
        System.out.println("寫入成功");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static String readCpu(String fileName) {
    String readed = "";
    File file = new File(fileName);
    if (!file.exists()) {
        return null;
    }
    try {
        FileInputStream fis = new FileInputStream(fileName);
        InputStreamReader is = new InputStreamReader(fis, "UTF-8");
        //fis.available()文件可用長度
        char input[] = new char[fis.available()];
        is.read(input);
        is.close();
        fis.close();
        readed = new String(input);
        Log.e("------readCpu", readed);
    } catch (FileNotFoundException e) {

        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return readed.trim();
}

/**
 * 獲取CPU溫度
 *
 * @return Cpu溫度
 * @throws IOException
 */
public static String getCpuTemp() throws IOException {
    String path = "/sys/devices/virtual/thermal/thermal_zone0/temp";
    File file = new File(path);
    String str = null;
    int i = 0;
    byte[] b = null;
    BufferedReader bufferedReader = null;
    if (file.exists()) {
        if (file.isFile()) {
            bufferedReader = new BufferedReader(new FileReader(file));
            str = bufferedReader.readLine();
        }
    }
    if (bufferedReader != null) {
        bufferedReader.close();
    }
    return str;
}

/**
 * 獲取cpu序列號
 *
 * @return
 * @throws IOException
 */
public static String getCpuSerial() throws IOException {
    String path = "/proc/cpuinfo";
    String str = getVersion(path, "Serial", ":");
    return str;
}

/**
 * 獲取硬件、驅動版本號
 *
 * @param path
 * @param world
 * @param separator 分割符,如a=b中的=
 * @return
 * @throws IOException
 */
public static String getVersion(String path, String world, String separator) {
    File file = new File(path);
    String str = null;
    BufferedReader bufferedReader = null;
    if (file.exists()) {
        if (file.isFile()) {
            try {
                bufferedReader = new BufferedReader(new FileReader(file));
                while ((str = bufferedReader.readLine()) != null) {
                    if (str.startsWith(world)) {
                        str = (str.substring(str.indexOf(separator) + 1, str.length())).trim();
                        System.out.println(str);
                        bufferedReader.close();
                        return str;
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
    return null;
}

public static String bitMapToBase64String(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    boolean ok = bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    String faceBimap;
    if (ok) {
        faceBimap = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
    } else {
        faceBimap = null;
    }
    return faceBimap;
}

// public static String getCpuSerial() throws IOException {
// String path = “/proc/cpuinfo”;
// File file = new File(path);
// String str = null;
// int i = 0;
// byte[] b ;
// FileInputStream fileInputStream = null;
//
// StringBuilder sb ;
// if (file.exists()){
// if (file.isFile()){
// b = new byte[20];
// fileInputStream = new FileInputStream(file);
// sb = new StringBuilder();
// while ((i = fileInputStream.read(b)) != -1){
// sb.append(new String(b, 0, i));
// }
// String content = sb.toString();
// int j = content.indexOf(“Serial”);
// content = content.substring(j, content.length());
// String[] strs = content.split(“:”);
// str = strs[strs.length-1].replace(“\n”, “”);
// }
// }
// if (fileInputStream != null){
// fileInputStream.close();
// }
// return str;
// }

//版本名
public static String getVersionName(Context context) {
    return getPackageInfo(context).versionName;
}

//版本號
public static int getVersionCode(Context context) {
    return getPackageInfo(context).versionCode;
}

private static PackageInfo getPackageInfo(Context context) {
    PackageInfo pi = null;

    try {
        PackageManager pm = context.getPackageManager();
        pi = pm.getPackageInfo(context.getPackageName(),
                PackageManager.GET_CONFIGURATIONS);

        return pi;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return pi;
}


/**
 * 判斷是否身份證
 *
 * @param num
 * @return
 */
public static boolean verForm(String num) {
    String reg = "^\\d{15}$|^\\d{17}[0-9Xx]$";
    if (!num.matches(reg)) {
        System.out.println("Format Error!");
        return false;
    }
    return true;
}

/**
 * 判斷身份證最後一位
 *
 * @param id
 * @return
 */
public static boolean verify(char[] id) {
    int sum = 0;
    int w[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    char[] ch = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
    for (int i = 0; i < id.length - 1; i++) {
        sum += (id[i] - '0') * w[i];
    }
    int c = sum % 11;
    char code = ch[c];
    char last = id[id.length - 1];
    last = last == 'x' ? 'X' : last;
    return last == code;
}


//    private static final String SD_PATH = "/sdcard/dskqxt/pic/";

// private static final String IN_PATH = “/dskqxt/pic/”;
private static int i = 0;

/**
 * 保存bitmap到本地
 *
 * @param mBitmap
 * @return
 */
public static String saveBitmap1(Bitmap mBitmap) {
    String SD_PATH = "/sdcard/facepic/pic/";
    i++;
    String savePath;
    File filePic;

// if (Environment.getExternalStorageState().equals(
// Environment.MEDIA_MOUNTED)) {
savePath = SD_PATH;
Log.e(“CameraView”, “saveBitmap1: ” + savePath);
// }
// else {
// savePath = getFilesDir()
// .getAbsolutePath()
// + IN_PATH;
// }
try {
filePic = new File(savePath + i + “.jpg”);
if (!filePic.exists()) {
filePic.getParentFile().mkdirs();
filePic.createNewFile();
}
FileOutputStream fos = new FileOutputStream(filePic);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}

    return filePic.getAbsolutePath();
}

public static Date getDate() {
    Date date = new Date(System.currentTimeMillis());
    return date;
}

//獲取打印次數
public static String getprintCount(String path) {
    String ptintCount = null;
    try {
        File file = new File(path);
        if (file.exists()) {
            if (file.isFile()) {
                BufferedInputStream bis = null;
                byte[] b = new byte[1024];
                bis = new BufferedInputStream(new FileInputStream(file));
                StringBuffer sb = new StringBuffer();
                int tempLen = 0;
                while ((tempLen = bis.read(b)) != -1) {
                    sb.append(new String(b, 0, tempLen));
                }
                ptintCount = sb.toString();
                bis.close();
                return ptintCount;
            } else {
                ptintCount = "-2";
            }
        } else {
            ptintCount = "-1";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

// Log.e(“Tool”, “打印次數=” + ptintCount);
return ptintCount;
}

//取得當前進程名
public static String getCurProcessName(Context context) {
    int pid = android.os.Process.myPid();
    ActivityManager mActivityManager = (ActivityManager) context
            .getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
            .getRunningAppProcesses()) {
        if (appProcess.pid == pid) {
            return appProcess.processName;
        }
    }
    return null;
}

public static String getCpuId() {
    String cpuId = null;
    try {
        cpuId = Tool.getCpuSerial();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return cpuId;
}

//http://zengjz88.iteye.com/blog/1595535#comments
//獲取單個進程的CPU使用率

public static double getProcCpu(int pid) {
Process process = null;
BufferedReader br = null;
try {
String procCpuShell = getCpuSerial();
if (“”.equals(procCpuShell)) return 0;
procCpuShell = procCpuShell.replaceAll(“$pid”, pid + “”);
String[] cmd = new String[]{“/bin/sh”, “-c”, procCpuShell};
process = Runtime.getRuntime().exec(cmd);
int resultCode = process.waitFor();
Log.d(“執行結果PID:”, pid + ” :” + resultCode);
br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
Double cpu = Double.parseDouble(line);
if (cpu > 100) cpu = cpu / 10;//剛啓動會出現CPU100多情況,則處理除於10
return cpu;
}
} catch (Exception e) {
Log.d(“執行獲取進程CPU使用率錯誤”, e.getMessage().toString());
} finally {
try {
if (process != null) process.destroy();
if (br != null) br.close();
} catch (Exception e) {
Log.d(“”, e.getMessage().toString());
}
}
return 0.0;
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章