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

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

分类: JAVA Android   203人阅读  评论(0)  收藏  举报
核心算法描述:

第一步:获取正在运行的进程, 保存在集合当中 : 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”错误。



获取正在运行的进程:
[java]  view plain copy print ?
  1.     /** 
  2.      * 获取正在运行的进程 
  3.      *  
  4.      * @return 
  5.      */  
  6.     public List<IsRunningAppInfo> queryRunningApp() {  
  7.   
  8.         List<IsRunningAppInfo> listRunApp = new ArrayList<IsRunningAppInfo>();  
  9.         am = (ActivityManager) context  
  10.                 .getSystemService(Context.ACTIVITY_SERVICE);  
  11.         List<RunningAppProcessInfo> list = am.getRunningAppProcesses();  
  12.         RunningAppProcessInfo runningPro = null;  
  13.         IsRunningAppInfo appInfo = null;  
  14.         for (int i = 0; i < list.size(); i++) {  
  15.   
  16.             runningPro = list.get(i);  
  17.             appInfo = new IsRunningAppInfo();  
  18.             appInfo.setPid(runningPro.pid);  
  19.             appInfo.setProcessName(runningPro.processName);  
  20.             appInfo.setUid(runningPro.uid);  
  21.             pkgManager(appInfo);  
  22.             listRunApp.add(appInfo);  
  23.         }  
  24.         return listRunApp;  
  25.     }  
  26.   
  27.     /** 
  28.      * 获取应用程序的 程序名,图标 
  29.      *  
  30.      * @param appInfo 
  31.      * @throws NameNotFoundException 
  32.      */  
  33.     public void pkgManager(IsRunningAppInfo appInfo) {  
  34.   
  35.         try {  
  36.             PackageManager pm = context.getPackageManager();  
  37.             PackageInfo pkInfo;  
  38.             pkInfo = pm.getPackageInfo(appInfo.getProcessName(), 0);  
  39.             appInfo.setIcon(pkInfo.applicationInfo.loadIcon(pm));  
  40.             appInfo.setAppName(pkInfo.applicationInfo.loadLabel(pm).toString());  
  41.         } catch (NameNotFoundException e) {  
  42.             e.printStackTrace();  
  43.         }  
  44.     }  
  45.   
  46. 读取CPU文件:  
  47.     public void cpuMain() {  
  48.         sqliteHelp  
  49.                 .clearAllTableData(new String[] {  
  50.                         Config.TBL_CPUMONITOR_PROCESSCPU,  
  51.                         Config.TBL_CPUMONITOR_TheadCPU,  
  52.                         Config.TBL_CPUMONITOR_TOTALCPU }); // 在读取文件前清空所有表数据  
  53.         R_W_File rw = new R_W_File();  
  54.         rw.clearFileData(new File(rw.getSdcardPath(), "result.txt"));  
  55.         i = 0;  
  56.         while (i < 2) {  
  57.             queryRunningApp(); // 获取正在运行的应用程序信息  
  58.             if (i == 0) {  
  59.                 readTotalCPU(i); // 捕捉时,总CPU  
  60.             }  
  61.             readProcessCPU(i); // 进程CPU--->线程CPU  
  62.             readThreadCPU(i);  
  63.             i++;  
  64.         }  
  65.     }  
  66.   
  67.     /** 
  68.      * 获取正在运行的应用程序 
  69.      */  
  70.     protected void queryRunningApp() {  
  71.   
  72.         IsRunningAppProgress pro = new IsRunningAppProgress(context);  
  73.         appList = pro.queryRunningApp();  
  74.     }  
  75.   
  76.     /** 
  77.      * 总CPU使用量 
  78.      */  
  79.     protected void readTotalCPU(int i) {  
  80.   
  81.         AsyncTask_TotalCPU taskTotalCPU = new AsyncTask_TotalCPU(context);  
  82.         taskTotalCPU.execute(i, nullnull);  
  83.     }  
  84.   
  85.     /** 
  86.      * 进程CPU 
  87.      */  
  88.     protected void readProcessCPU(int i) {  
  89.         AsyncTask_ProgressCPU taskProcessCPU = null;  
  90.         taskProcessCPU = new AsyncTask_ProgressCPU(new ProcessCallback(),  
  91.                 appList);  
  92.         taskProcessCPU.execute(i, nullnull);  
  93.     }  
  94.   
  95.     /** 
  96.      * 线程CPU 
  97.      */  
  98.     protected void readThreadCPU(int i) {  
  99.         AsyncTask_TheadCPU taskThreadCPU = new AsyncTask_TheadCPU(  
  100.                 new ThreadCallback(), appList);  
  101.         taskThreadCPU.execute(i, nullnull);  
  102.     }  
  103.   
  104.     /** 
  105.      * 回调方法 
  106.      */  
  107.     class ThreadCallback implements ICallbacks {  
  108.   
  109.         @Override  
  110.         public <T> void call(T t1, T t2) {  
  111.             if ((Integer) t2 == 1) {  
  112.                 readTotalCPU(1); // 捕捉时,总CPU  
  113.             }  
  114.             @SuppressWarnings("unchecked")  
  115.             Map<String[], IsRunningAppInfo> saveThreadCPUMap = (Map<String[], IsRunningAppInfo>) t1;  
  116.             saveThreadData(saveThreadCPUMap, (Integer) t2);  
  117.         }  
  118.     }  
  119.   
  120.     /** 
  121.      * 回调方法 
  122.      */  
  123.     class ProcessCallback implements ICallbacks {  
  124.   
  125.         @Override  
  126.         public <T> void call(T t1, T t2) {  
  127.             @SuppressWarnings("unchecked")  
  128.             Map<String[], IsRunningAppInfo> saveProCPUMap = (Map<String[], IsRunningAppInfo>) t1;  
  129.             saveProData(saveProCPUMap, (Integer) t2);  
  130.         }  
  131.     }  
  132.   
  133.     public void saveThreadData(  
  134.             Map<String[], IsRunningAppInfo> saveThreadCPUMap, int j) {  
  135.   
  136.         Set<String[]> key = saveThreadCPUMap.keySet();  
  137.         Iterator<String[]> it = key.iterator();  
  138.         String[] str = null;  
  139.         IsRunningAppInfo appInfo = null;  
  140.         ContentValues cv = null;  
  141.         while (it.hasNext()) {  
  142.             str = it.next();  
  143.             appInfo = saveThreadCPUMap.get(str);  
  144.             cv = new ContentValues();  
  145.             cv.put("processName", appInfo.getProcessName());  
  146.             cv.put("pid", appInfo.getPid());  
  147.             cv.put("tid", Long.valueOf(str[0]));  
  148.             cv.put("utime", Long.valueOf(str[13]));  
  149.             cv.put("stime", Long.valueOf(str[14]));  
  150.             cv.put("numTimes", j);  
  151.             sqliteHelp.append(Config.TBL_CPUMONITOR_TheadCPU, cv);  
  152.         }  
  153.         if (j == 1) {  
  154.             writeData();  
  155.         }  
  156.     }  
  157.   
  158.     /** 
  159.      * 保存进程数据 
  160.      *  
  161.      * @param saveProCPUMap 
  162.      * @param j 
  163.      */  
  164.     private void saveProData(Map<String[], IsRunningAppInfo> saveProCPUMap,  
  165.             int j) {  
  166.   
  167.         Set<String[]> key = saveProCPUMap.keySet();  
  168.         Iterator<String[]> it = key.iterator();  
  169.         String[] str = null;  
  170.         IsRunningAppInfo runApp = null;  
  171.         ContentValues cv = null;  
  172.         while (it.hasNext()) {  
  173.             str = it.next();  
  174.             runApp = saveProCPUMap.get(str);  
  175.             cv = new ContentValues();  
  176.             if (runApp.getIcon() == null) {  
  177.                 cv.put("icon",  
  178.                         FormatImage.getInstace().getDrawableToByte(  
  179.                                 context.getResources().getDrawable(  
  180.                                         R.drawable.ic_launcher_default)));  
  181.             } else  
  182.                 cv.put("icon",  
  183.                         FormatImage.getInstace().getDrawableToByte(  
  184.                                 runApp.getIcon()));  
  185.             if (runApp.getAppName() == null || runApp.getAppName().equals("")) {  
  186.                 cv.put("appName", runApp.getProcessName());  
  187.             } else  
  188.                 cv.put("appName", runApp.getAppName());  
  189.             cv.put("processName", runApp.getProcessName());  
  190.             cv.put("pid", runApp.getPid());  
  191.             cv.put("utime", str[13]);  
  192.             cv.put("stime", str[14]);  
  193.             cv.put("cutime", str[15]);  
  194.             cv.put("cstime", str[16]);  
  195.             cv.put("numTimes", j);  
  196.             sqliteHelp.append(Config.TBL_CPUMONITOR_PROCESSCPU, cv);  
  197.         }  
  198.         if (j == 1) {  
  199.             writeData();  
  200.         }  
  201.     }  
  202.   
  203.     public void writeData() {  
  204.         try {  
  205.             R_W_File files = new R_W_File();  
  206.             File mFile = new File(files.getSdcardPath(), "result.txt");  
  207.             files.writeFileDataAtTail(mFile, "1");  
  208.         } catch (IOException e) {  
  209.             e.printStackTrace();  
  210.         }  
  211.     }  
  212. }  
  213. 显示CPU列表数据:  
  214. public View getView(int position, View convertView, ViewGroup parent) {  
  215.   
  216.         ProcessCPU pro = list.get(position);  
  217.   
  218.         if (convertView == null) {  
  219.             convertView = inflater.inflate(layoutId, null);  
  220.             appView = new AppView(convertView);  
  221.             convertView.setTag(appView);  
  222.         } else {  
  223.             appView = (AppView) convertView.getTag();  
  224.         }  
  225.         appView.pkgName.setText(pro.getProcessName());  
  226.         appView.appIcon.setBackgroundDrawable(pro.getIcon()); // 图标  
  227.         appView.appName.setText(pro.getAppName()); // 应用名  
  228.         appView.pb.setMax(100);  
  229.         if (pro.getProcessName().equals("system"))  
  230.             Log.e("systemValue:" + pro.getUtime() + "  ==totalCPU:" + totalCPU);  
  231.         double schedule = Double.valueOf(String.format("%.2f", pro.getUtime()  
  232.                 * 100.00 / totalCPU));  
  233.         appView.pb.setProgress((int) schedule);  
  234.         appView.tvPb.setText("" + schedule + "%");  
  235.   
  236.         return convertView;  
  237.     }  
  238. handle中读取并显示数据:  
  239.   
  240.     @Override  
  241.     public void handleMessage(Message msg) {  
  242.         super.handleMessage(msg);  
  243.   
  244.         dialog = (Dialog) msg.obj;  
  245.   
  246.         queryTotalCPU();  
  247.         queryProcessList();  
  248.   
  249.         if (adapterCpuChart == null) {  
  250.             adapterCpuChart = new Adapter_cpu_chart(context,  
  251.                     R.layout.adapter_cpu_chart, list, totalCPU);  
  252.         }  
  253.         lvChart.setAdapter(adapterCpuChart);  
  254.         adapterCpuChart.notifyDataSetChanged();  
  255.         pbBar.closeDialogProgressBar(dialog);  
  256.     }  
  257.   
  258.     /** 
  259.      * 查找总共CPU时间片 每次进行数据查询的时候,将表中的数据重新请空 
  260.      */  
  261.     public void queryTotalCPU() {  
  262.   
  263.         sql = "select (max(num1)-min(num1)) as total from "  
  264.                 + "(select (t.user+t.nice+t.system+t.iowait+t.irq+t.softirq+t.stealstolen+t.guest) as num1 "  
  265.                 + "from TotalCPU t)";  
  266.         cursor = sqliteHelp.query(sql);  
  267.         int index = -1;  
  268.         long allValue = -1;  
  269.         long ownValue = -1;  
  270.         long ownThreadCPU = -1;  
  271.         if (cursor.moveToFirst()) {  
  272.             index = cursor.getColumnIndex("total");  
  273.             allValue = cursor.getLong(index);  
  274.         }  
  275.         sqliteHelp.closeDb();  
  276.         sql = "select  (max(num2)-min(num2)) as ownCPU from (select (p.utime+p.stime+p.cstime+p.cutime) as num2 "  
  277.                 + "from ProcessCPU p "  
  278.                 + "where p.processName='"  
  279.                 + pkgName  
  280.                 + "') ";  
  281.         cursor = sqliteHelp.query(sql);  
  282.         if (cursor.moveToFirst()) {  
  283.             index = cursor.getColumnIndex("ownCPU");  
  284.             ownValue = cursor.getLong(index);  
  285.         }  
  286.         sqliteHelp.closeDb();  
  287.   
  288.         sql = "select  max(num3)-min(num3) as ownThreadCPU "  
  289.                 + "from (select (t.utime+t.stime) as num3 "  
  290.                 + "from ThreadCPU t " + "where t.processName='" + pkgName  
  291.                 + "') ";  
  292.         cursor = sqliteHelp.query(sql);  
  293.         if (cursor.moveToFirst()) {  
  294.             index = cursor.getColumnIndex("ownThreadCPU");  
  295.             ownThreadCPU = cursor.getLong(index);  
  296.         }  
  297.         sqliteHelp.closeDb();  
  298.   
  299.         totalCPU = (allValue - ownValue - ownThreadCPU);  
  300.         Log.e("allValue:" + allValue + "  " + " ownValue:" + ownValue  
  301.                 + "  ownThreadCPU" + ownThreadCPU);  
  302.     }  
  303.   
  304.     /** 
  305.      * 查找所有进程的CPU时间片 
  306.      */  
  307.     public void queryProcessList() {  
  308.         sql = "select p.processName,p.appName,p.icon,sum(temp.utime) as utime "  
  309.                 + "from (select processName,(max(utime)-min(utime)) as utime "  
  310.                 + "from (select processName,appName,icon, (utime+stime+cutime+cstime) as utime "  
  311.                 + "from ProcessCPU where processName <> '"  
  312.                 + pkgName  
  313.                 + "' and numTimes=0 "  
  314.                 + "union all "  
  315.                 + "select processName,appName,icon, (utime+stime+cutime+cstime) as utime "  
  316.                 + "from ProcessCPU where processName <> '"  
  317.                 + pkgName  
  318.                 + "' and numTimes=1 ) "  
  319.                 + "group by processName "  
  320.                 + "union all select processName,(max(utime)-min(utime)) as utime "  
  321.                 + "from (select processName, sum(utime+stime) as utime "  
  322.                 + "from ThreadCPU where processName <> '"  
  323.                 + pkgName  
  324.                 + "' and numTimes=0 "  
  325.                 + "group by processName union all select processName, sum(utime+stime) as utime "  
  326.                 + "from ThreadCPU where processName <> '"  
  327.                 + pkgName  
  328.                 + "' and numTimes=1 "  
  329.                 + "group by processName) group by processName) as temp,ProcessCPU p "  
  330.                 + "where p.processName=temp.processName group by p.processName "  
  331.                 + "order by utime desc limit 10";  
  332.         list = new ArrayList<ProcessCPU>();  
  333.         cursor = sqliteHelp.query(sql);  
  334.         ProcessCPU proCPU = null;  
  335.         if (cursor.moveToFirst()) {  
  336.             do {  
  337.                 proCPU = new ProcessCPU();  
  338.                 int processName = cursor.getColumnIndex("processName");  
  339.                 int appName = cursor.getColumnIndex("appName");  
  340.                 int icon = cursor.getColumnIndex("icon");  
  341.                 int utime = cursor.getColumnIndex("utime");  
  342.                 proCPU.setAppName(cursor.getString(appName));  
  343.                 proCPU.setProcessName(cursor.getString(processName));  
  344.                 proCPU.setIcon(FormatImage.getInstace().getByteToDrawable(  
  345.                         cursor.getBlob(icon)));  
  346.                 proCPU.setUtime(cursor.getLong(utime));  
  347.                 list.add(proCPU);  
  348.             } while (cursor.moveToNext());  
  349.         }  
  350.         sqliteHelp.closeDb();  
  351.     }  
  352.   
  353. 读取进程CPU:  
  354. public void readFile() {  
  355.   
  356.         String[] str = null;  
  357.         for (int i = 0; i < list.size(); i++) {  
  358.   
  359.             runApp = list.get(i);  
  360.             file = new File(getPath(runApp.getPid()));  
  361.             try {  
  362.                 fis = new FileInputStream(file);  
  363.                 br = new BufferedReader(new InputStreamReader(fis));  
  364.                 String readLine;  
  365.                 while ((readLine = br.readLine()) != null) {  
  366.                     str = readLine.split(" ");  
  367.                 }  
  368.                 br.close();  
  369.                 fis.close();  
  370.             } catch (FileNotFoundException e) {  
  371.                 e.printStackTrace();  
  372.             } catch (IOException e) {  
  373.                 e.printStackTrace();  
  374.             }  
  375.             saveProCPUMap.put(str, runApp);  
  376.         }  
  377.     }  
  378.   
  379.     /** 
  380.      * 获取每个进程的 文件路径 
  381.      *  
  382.      * @param pid 
  383.      * @return 
  384.      */  
  385.     public String getPath(long pid) {  
  386.         return "/proc/" + pid + "/stat";  
  387.     }  
  388. 读取线程CPU:  
  389.     public void queryThreadCPU(List<IsRunningAppInfo> list) throws IOException {  
  390.         for (int i = 0; i < list.size(); i++) {  
  391.             IsRunningAppInfo appInfo = list.get(i);  
  392.             queryThreadCPU(appInfo);  
  393.         }  
  394.     }  
  395.   
  396.     /** 
  397.      * 根据每一个pid获取CPU使用率 
  398.      *  
  399.      * @param pid 
  400.      * @return 
  401.      * @throws IOException 
  402.      */  
  403.     public void queryThreadCPU(IsRunningAppInfo appInfo) throws IOException {  
  404.   
  405.         path = "/proc/" + appInfo.getPid() + "/task";  
  406.         file = new File(path);  
  407.         if (file.exists() && file != null) {  
  408.   
  409.             files = file.listFiles();  
  410.             if (files != null) {  
  411.                 queryThreadCPU(files, appInfo);  
  412.             }  
  413.         }  
  414.     }  
  415.   
  416.     /** 
  417.      * 查询某一个进程的 线程CPU使用情况 
  418.      *  
  419.      * @param files 
  420.      * @return 
  421.      * @throws IOException 
  422.      */  
  423.     private void queryThreadCPU(File[] files, IsRunningAppInfo appInfo)  
  424.             throws IOException {  
  425.         String readLine;  
  426.         String[] tStr = null;  
  427.         for (int i = 0; i < files.length; i++) {  
  428.             File f = files[i];  
  429.             path = f.getPath() + "/stat";  
  430.   
  431.             file = new File(path);  
  432.             fis = new FileInputStream(file);  
  433.             br = new BufferedReader(new InputStreamReader(fis));  
  434.             while ((readLine = br.readLine()) != null) {  
  435.                 tStr = readLine.split(" ");  
  436.             }  
  437.         }  
  438.         saveThreadCPUMap.put(tStr, appInfo);  
  439.     }  
  440.   
  441.     @Override  
  442.     protected void onPostExecute(Void result) {  
  443.         super.onPostExecute(result);  
  444.     }  
  445. 读取总CPU:  
  446.     public Long readFile() {  
  447.   
  448.         String[] str = null;  
  449.         file = new File(path);  
  450.         try {  
  451.             fis = new FileInputStream(file);  
  452.             br = new BufferedReader(new InputStreamReader(fis));  
  453.             String readLine;  
  454.             if ((readLine = br.readLine()) != null) {  
  455.                 str = readLine.split(" ");  
  456.             }  
  457.             br.close();  
  458.             fis.close();  
  459.         } catch (FileNotFoundException e) {  
  460.             e.printStackTrace();  
  461.         } catch (IOException e) {  
  462.             e.printStackTrace();  
  463.         }  
  464.         return changeArray(str);  
  465.     }  
  466.   
  467.     private Long changeArray(String[] str) {  
  468.         Log.e("长度:" + str.length);  
  469.         ContentValues cv = new ContentValues();  
  470.         cv.put("user", Long.valueOf(str[2]));  
  471.         cv.put("nice", Long.valueOf(str[3]));  
  472.         cv.put("system", Long.valueOf(str[4]));  
  473.         cv.put("idle", Long.valueOf(str[5]));  
  474.         cv.put("iowait", Long.valueOf(str[6]));  
  475.         cv.put("irq", Long.valueOf(str[7]));  
  476.         cv.put("softirq", Long.valueOf(str[8]));  
  477.         cv.put("stealstolen", Long.valueOf(str[9]));  
  478.         cv.put("guest", Long.valueOf(str[10]));  
  479.         cv.put("numTimes", i);  
  480.         return sqliteHelp.append(Config.TBL_CPUMONITOR_TOTALCPU, cv);  
  481.     }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值