当前位置:操作系统 > 安卓/Android >>

Android CPU监控想法,思路,核心技术和代码

核心算法描述:
 
第一步:获取正在运行的进程, 保存在集合当中 : List<IsRunningAppInfo> appList
 
第二步:读取总使用的CPU,  路径在  private static String path = "/proc/stat";
 
第三步:读取所有运行进程CPU,路径在  "/proc/" + pid + "/stat";  //pid为进程号
 
第四步:读取所有运行线程CPU,路径在 "/proc/" + pid + "/task" + tid +"/stat";   //pid为进程号,tid为线程号
 
第五步:读取好文件的信息,分别保存在不同集合当中,然后回调回去,存入数据库(根据需求,可灵活运用),避免一边读取文件,一边保存数据库当中,不然将耗费大量的时间,产生的误差特别的大
 
第六步:数据的内容保存好后,到另外一个activity中,从数据库中读取数据,并列表显示出数据。
注意:读取的时候,可能会碰到读取文件的内容的时候,还没有读好(算所占比例的时候会出现出现“除数为0”),需要定义一个handle,在handle当中读取数据(读的过程中,判断是否数据存储完毕),并显示读取的数据,不能在activity当中不然会出现“AndroidRunTime”错误。
 
 
 
获取正在运行的进程:
 
    /** 
     * 获取正在运行的进程 
     *  
     * @return 
     */  
    public List<IsRunningAppInfo> queryRunningApp() {  
  
        List<IsRunningAppInfo> listRunApp = new ArrayList<IsRunningAppInfo>();  
        am = (ActivityManager) context  
                .getSystemService(Context.ACTIVITY_SERVICE);  
        List<RunningAppProcessInfo> list = am.getRunningAppProcesses();  
        RunningAppProcessInfo runningPro = null;  
        IsRunningAppInfo appInfo = null;  
        for (int i = 0; i < list.size(); i++) {  
  
            runningPro = list.get(i);  
            appInfo = new IsRunningAppInfo();  
            appInfo.setPid(runningPro.pid);  
            appInfo.setProcessName(runningPro.processName);  
            appInfo.setUid(runningPro.uid);  
            pkgManager(appInfo);  
            listRunApp.add(appInfo);  
        }  
        return listRunApp;  
    }  
  
    /** 
     * 获取应用程序的 程序名,图标 
     *  
     * @param appInfo 
     * @throws NameNotFoundException 
     */  
    public void pkgManager(IsRunningAppInfo appInfo) {  
  
        try {  
            PackageManager pm = context.getPackageManager();  
            PackageInfo pkInfo;  
            pkInfo = pm.getPackageInfo(appInfo.getProcessName(), 0);  
            appInfo.setIcon(pkInfo.applicationInfo.loadIcon(pm));  
            appInfo.setAppName(pkInfo.applicationInfo.loadLabel(pm).toString());  
        } catch (NameNotFoundException e) {  
            e.printStackTrace();  
        }  
    }  
  
读取CPU文件:  
    public void cpuMain() {  
        sqliteHelp  
                .clearAllTableData(new String[] {  
                        Config.TBL_CPUMONITOR_PROCESSCPU,  
                        Config.TBL_CPUMONITOR_TheadCPU,  
                        Config.TBL_CPUMONITOR_TOTALCPU }); // 在读取文件前清空所有表数据  
        R_W_File rw = new R_W_File();  
        rw.clearFileData(new File(rw.getSdcardPath(), "result.txt"));  
        i = 0;  
        while (i < 2) {  
            queryRunningApp(); // 获取正在运行的应用程序信息  
            if (i == 0) {  
                readTotalCPU(i); // 捕捉时,总CPU  
            }  
            readProcessCPU(i); // 进程CPU--->线程CPU  
            readThreadCPU(i);  
            i++;  
        }  
    }  
  
    /** 
     * 获取正在运行的应用程序 
     */  
    protected void queryRunningApp() {  
  
        IsRunningAppProgress pro = new IsRunningAppProgress(context);  
        appList = pro.queryRunningApp();  
    }  
  
    /** 
     * 总CPU使用量 
     */  
    protected void readTotalCPU(int i) {  
  
        AsyncTask_TotalCPU taskTotalCPU = new AsyncTask_TotalCPU(context);  
        taskTotalCPU.execute(i, null, null);  
    }  
  
    /** 
     * 进程CPU 
     */  
    protected void readProcessCPU(int i) {  
        AsyncTask_ProgressCPU taskProcessCPU = null;  
        taskProcessCPU = new AsyncTask_ProgressCPU(new ProcessCallback(),  
                appList);  
        taskProcessCPU.execute(i, null, null);  
    }  
  
    /** 
     * 线程CPU 
     */  
    protected void readThreadCPU(int i) {  
        AsyncTask_TheadCPU taskThreadCPU = new AsyncTask_TheadCPU(  
                new ThreadCallback(), appList);  
        taskThreadCPU.execute(i, null, null);  
    }  
  
    /** 
     * 回调方法 
     */  
    class ThreadCallback implements ICallbacks {  
  
        @Override  
        public <T> void call(T t1, T t2) {  
            if ((Integer) t2 == 1) {  
                readTotalCPU(1); // 捕捉时,总CPU  
            }  
            @SuppressWarnings("unchecked")  
            Map<String[], IsRunningAppInfo> saveThreadCPUMap = (Map<String[], IsRunningAppInfo>) t1;  
            saveThreadData(saveThreadCPUMap, (Integer) t2);  
        }  
    }  
  
    /** 
     * 回调方法 
     */  
    class ProcessCallback implements ICallbacks {  
  
        @Override  
        public <T> void call(T t1, T t2) {  
            @SuppressWarnings("unchecked")  
            Map<String[], IsRunningAppInfo> saveProCPUMap = (Map<String[], IsRunningAppInfo>) t1;  
            saveProData(saveProCPUMap, (Integer) t2);  
        }  
    }  
  
    public void saveThreadData(  
            Map<String[], IsRunningAppInfo> saveThreadCPUMap, int j) {  
  
        Set<String[]> key = saveThreadCPUMap.keySet();  
        Iterator<String[]> it = key.iterator();  
        String[] str = null;  
        IsRunningAppInfo appInfo = null;  
        ContentValues cv = null;  
        while (it.hasNext()) {  
            str = it.next();  
            appInfo = saveThreadCPUMap.get(str);  
            cv = new ContentValues();  
            cv.put("processName", appInfo.getProcessName());  
            cv.put("pid", appInfo.getPid());  
            cv.put("tid", Long.valueOf(str[0]));  
            cv.put("utime", Long.valueOf(str[13]));  
            cv.put("stime", Long.valueOf(str[14]));  
            cv.put("numTimes", j);  
            sqliteHelp.append(Config.TBL_CPUMONITOR_TheadCPU, cv);  
        }  
        if (j == 1) {  
            writeData();  
        }  
    }  
  
    /** 
     * 保存进程数据 
     *  
     * @param saveProCPUMap 
     * @param j 
     */  
    private void saveProData(Map<String[], IsRunningAppInfo> saveProCPUMap,  
            int j) {  
  
        Set<String[]> key = saveProCPUMap.keySet();  
        Iterator<String[]> it = key.iterator();  
        String[] str = null;  
        IsRunningAppInfo runApp = null;  
        ContentValues cv = null;  
        while (it.hasNext()) {  
            str = it.next();  
            runApp = saveProCPUMap.get(str);  
            cv = new ContentValues();  
            if (runApp.getIcon() == null) {  
                cv.put("icon",  
                        FormatImage.getInstace().getDrawableToByte(  
                                context.getResources().getDrawable(  
                                        R.drawable.ic_launcher_default)));  
            } else  
                cv.put("icon",  
                        FormatImage.getInstace().getDrawableToByte(  
                                runApp.getIcon()));  
            if (runApp.getAppName() == null || runApp.getAppName().equals("")) {  
                cv.put("appName", runApp.getProcessName());  
            } else  
                cv.put("appName", runApp.getAppName());  
            cv.put("processName", runApp.getProcessName());  
            c
补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,