Emmagee源码学习

Emmagee是监控指定被测应用在使用过程中占用机器的CPU、内存、流量资源的性能测试小工具。项目如图:


主要源码分析:

[java] view
plain
 copy

  1. public class CpuInfo { //测试cpu 封装cpu信息 当前时间被测应用占用的CPU使用率以及总体CPU使用量   
[java] view
plain
 copy

  1. public class EncryptData {  //提供加密算法,可以对输入的字符串进行加密、解密操作  
[java] view
plain
 copy

  1. public class MailSender {   //发送邮件给多个接收者、抄送邮件  
[java] view
plain
 copy

  1. public class MemoryInfo {   //操作内存 封装内存消息 当前时间被测应用占用的内存量,以及占用的总体内存百分比,剩余内存量  
[java] view
plain
 copy

  1. public class ProcessInfo {  //获得进程消息   
[java] view
plain
 copy

  1. public class TrafficInfo {  //流量 信息 应用从启动开始到当前时间消耗的流量数  
[java] view
plain
 copy

  1. public class EmmageeService extends Service { //关键服务 所有的操作都基于该服务 操作如下:  
[java] view
plain
 copy

  1. private void readSettingInfo(Intent intent) {   //读取配置文件  
  2.     try {  
  3.         Properties properties = new Properties();  
  4.         properties.load(new FileInputStream(settingTempFile));  
  5.         String interval = properties.getProperty("interval").trim();  
  6.         isFloating = "true"  
  7.                 .equals(properties.getProperty("isfloat").trim()) ? true  
  8.                 : false;  
  9.         sender = properties.getProperty("sender").trim();  
  10.         password = properties.getProperty("password").trim();  
  11.         recipients = properties.getProperty("recipients").trim();  
  12.         time = "".equals(interval) ? "5" : interval;  
  13.         recipients = properties.getProperty("recipients");  
  14.         receivers = recipients.split("\s+");  
  15.         smtp = properties.getProperty("smtp");  
  16.     } catch (IOException e) {  
  17.         time = "5";  
  18.         isFloating = true;  
  19.         Log.e(LOG_TAG, e.getMessage());  
  20.     }  
  21. }  
[java] view
plain
 copy

  1. private void createResultCsv() {    //创建保存文件  
  2.     //测试数据写入到CSV文件中,同时存储在手机中  
  3.     Calendar cal = Calendar.getInstance();  
  4.     SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");  
  5.     String mDateTime;  
  6.     if ((Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk")))  
  7.         mDateTime = formatter.format(cal.getTime().getTime() + 8 * 60 * 60  
  8.                 * 1000);  
  9.     else  
  10.         mDateTime = formatter.format(cal.getTime().getTime());  
  11.   
  12.     if (android.os.Environment.getExternalStorageState().equals(  
  13.             android.os.Environment.MEDIA_MOUNTED)) {  
  14.         resultFilePath = android.os.Environment  
  15.                 .getExternalStorageDirectory()  
  16.                 + File.separator  
  17.                 + "Emmagee_TestResult_" + mDateTime + ".csv";  
  18.     } else {  
  19.         resultFilePath = getBaseContext().getFilesDir().getPath()  
  20.                 + File.separator + "Emmagee_TestResult_" + mDateTime  
  21.                 + ".csv";  
  22.     }  
  23.     try {  
  24.         File resultFile = new File(resultFilePath);  
  25.         resultFile.createNewFile();  
  26.         out = new FileOutputStream(resultFile);  
  27.         osw = new OutputStreamWriter(out, "GBK");  
  28.         bw = new BufferedWriter(osw);  
  29.         long totalMemorySize = memoryInfo.getTotalMemory();  
  30.         String totalMemory = fomart.format((double) totalMemorySize / 1024);  
  31.         bw.write("指定应用的CPU内存监控情况rn" + "应用包名:," + packageName + "rn"  
  32.                 + "应用名称: ," + processName + "rn" + "应用PID: ," + pid  
  33.                 + "rn" + "机器内存大小(MB):," + totalMemory + "MBrn"  
  34.                 + "机器CPU型号:," + cpuInfo.getCpuName() + "rn"  
  35.                 + "机器android系统版本:," + memoryInfo.getSDKVersion() + "rn"  
  36.                 + "手机型号:," + memoryInfo.getPhoneType() + "rn" + "UID:,"  
  37.                 + uid + "rn");  
  38.         bw.write("时间" + "," + "应用占用内存PSS(MB)" + "," + "应用占用内存比(%)" + ","  
  39.                 + " 机器剩余内存(MB)" + "," + "应用占用CPU率(%)" + "," + "CPU总使用率(%)"  
  40.                 + "," + "流量(KB):" + "rn");  
  41.     } catch (IOException e) {  
  42.         Log.e(LOG_TAG, e.getMessage());  
  43.     }  
  44. }  
[java] view
plain
 copy

  1. private void createFloatingWindow() {   //创建浮动窗口  
  2.     //可以选择开启浮窗功能,浮窗中实时显示被测应用占用性能数据信息  
  3.     //在浮窗中可以快速启动或者关闭手机的wifi网络  
  4.     SharedPreferences shared = getSharedPreferences("float_flag",  
  5.             Activity.MODE_PRIVATE);  
  6.     SharedPreferences.Editor editor = shared.edit();  
  7.     editor.putInt("float"1);  
  8.     editor.commit();  
  9.     windowManager = (WindowManager) getApplicationContext()  
  10.             .getSystemService("window");  
  11.     wmParams = ((MyApplication) getApplication()).getMywmParams();  
  12.     wmParams.type = 2002;  
  13.     wmParams.flags |= 8;  
  14.     wmParams.gravity = Gravity.LEFT | Gravity.TOP;  
  15.     wmParams.x = 0;  
  16.     wmParams.y = 0;  
  17.     wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;  
  18.     wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;  
  19.     wmParams.format = 1;  
  20.     windowManager.addView(viFloatingWindow, wmParams);  
  21.     viFloatingWindow.setOnTouchListener(new OnTouchListener() {  
  22.         public boolean onTouch(View v, MotionEvent event) {  
  23.             x = event.getRawX();  
  24.             y = event.getRawY() - 25;  
  25.             switch (event.getAction()) {  
  26.             case MotionEvent.ACTION_DOWN:  
  27.                 // state = MotionEvent.ACTION_DOWN;  
  28.                 startX = x;  
  29.                 startY = y;  
  30.                 mTouchStartX = event.getX();  
  31.                 mTouchStartY = event.getY();  
  32.                 Log.d("startP""startX" + mTouchStartX + "====startY"  
  33.                         + mTouchStartY);  
  34.                 break;  
  35.             case MotionEvent.ACTION_MOVE:  
  36.                 // state = MotionEvent.ACTION_MOVE;  
  37.                 updateViewPosition();  
  38.                 break;  
  39.   
  40.             case MotionEvent.ACTION_UP:  
  41.                 // state = MotionEvent.ACTION_UP;  
  42.                 updateViewPosition();  
  43.                 showImg();  
  44.                 mTouchStartX = mTouchStartY = 0;  
  45.                 break;  
  46.             }  
  47.             return true;  
  48.         }  
  49.     });  
  50.   
  51.     btnWifi.setOnClickListener(new OnClickListener() {  
  52.         @Override  
  53.         public void onClick(View v) {  
  54.             try {  
  55.                 btnWifi = (Button) viFloatingWindow.findViewById(R.id.wifi);  
  56.                 String buttonText = (String) btnWifi.getText();  
  57.                 String wifiText = getResources().getString(  
  58.                         R.string.openwifi);  
  59.                 if (buttonText.equals(wifiText)) {  
  60.                     wifiManager.setWifiEnabled(true);  
  61.                     btnWifi.setText(R.string.closewifi);  
  62.                 } else {  
  63.                     wifiManager.setWifiEnabled(false);  
  64.                     btnWifi.setText(R.string.openwifi);  
  65.                 }  
  66.             } catch (Exception e) {  
  67.                 Toast.makeText(viFloatingWindow.getContext(), "操作wifi失败",  
  68.                         Toast.LENGTH_LONG).show();  
  69.                 Log.e(LOG_TAG, e.toString());  
  70.             }  
  71.         }  
  72.     });  
  73. }  
[java] view
plain
 copy

  1. private void dataRefresh() {//刷新数据  
  2.     int pidMemory = memoryInfo.getPidMemorySize(pid, getBaseContext());  
  3.     long freeMemory = memoryInfo.getFreeMemorySize(getBaseContext());  
  4.     String freeMemoryKb = fomart.format((double) freeMemory / 1024);  
  5.     String processMemory = fomart.format((double) pidMemory / 1024);  
  6.     ArrayList<String> processInfo = cpuInfo.getCpuRatioInfo();  
  7.     if (isFloating) {  
  8.         String processCpuRatio = "0";  
  9.         String totalCpuRatio = "0";  
  10.         String trafficSize = "0";  
  11.         int tempTraffic = 0;  
  12.         double trafficMb = 0;  
  13.         boolean isMb = false;  
  14.         if (!processInfo.isEmpty()) {  
  15.             processCpuRatio = processInfo.get(0);  
  16.             totalCpuRatio = processInfo.get(1);  
  17.             trafficSize = processInfo.get(2);  
  18.             if ("".equals(trafficSize) && !("-1".equals(trafficSize))) {  
  19.                 tempTraffic = Integer.parseInt(trafficSize);  
  20.                 if (tempTraffic > 1024) {  
  21.                     isMb = true;  
  22.                     trafficMb = (double) tempTraffic / 1024;  
  23.                 }  
  24.             }  
  25.         }  
  26.         if ("0".equals(processMemory) && "0.00".equals(processCpuRatio)) {  
  27.             closeOpenedStream();  
  28.             isServiceStop = true;  
  29.             return;  
  30.         }  
  31.         if (processCpuRatio != null && totalCpuRatio != null) {  
  32.             txtUnusedMem.setText("占用内存:" + processMemory + "MB" + ",机器剩余:"  
  33.                     + freeMemoryKb + "MB");  
  34.             txtTotalMem.setText("占用CPU:" + processCpuRatio + "%"  
  35.                     + ",总体CPU:" + totalCpuRatio + "%");  
  36.             if ("-1".equals(trafficSize)) {  
  37.                 txtTraffic.setText("本程序或本设备不支持流量统计");  
  38.             } else if (isMb)  
  39.                 txtTraffic.setText("消耗流量:" + fomart.format(trafficMb)  
  40.                         + "MB");  
  41.             else  
  42.                 txtTraffic.setText("消耗流量:" + trafficSize + "KB");  
  43.         }  
  44.     }  
  45. }