获取单个进程cpu使用效率

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/nihaozhanghua/article/details/79268835

//获取单个进程的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;
}
}

展开阅读全文

没有更多推荐了,返回首页