提交 2e1bdf67 编写于 作者: A andrewleo

new features:add battery monitoring and quad-core CPU

上级 d4ec6c24
...@@ -7,5 +7,6 @@ ...@@ -7,5 +7,6 @@
<classpathentry kind="lib" path="libs/activation.jar"/> <classpathentry kind="lib" path="libs/activation.jar"/>
<classpathentry kind="lib" path="libs/mail.jar"/> <classpathentry kind="lib" path="libs/mail.jar"/>
<classpathentry kind="lib" path="libs/additionnal.jar"/> <classpathentry kind="lib" path="libs/additionnal.jar"/>
<classpathentry kind="lib" path="libs/android-support-v4.jar"/>
<classpathentry kind="output" path="bin/classes"/> <classpathentry kind="output" path="bin/classes"/>
</classpath> </classpath>
##Emmagee - a practical, handy performance test tool for specified Android App ##Emmagee - a practical, handy performance test tool for specified Android App
Emmagee is a practical, handy performance test tool for specified Android App, which can monitor CPU, memory and Emmagee is a practical, handy performance test tool for specified Android App, which can monitor CPU, memory,
network traffic. Additionally, it also provides several cool features such as customizing interval of collecting data, network traffic, battery current and status([Some devices are not supported](https://github.com/NetEase/Emmagee/wiki/Some-devices-are-not-supported)). Additionally, it also provides several cool features such as customizing interval of collecting data,
rendering real-time process status in a floating window, and much more. rendering real-time process status in a floating window, and much more.
* Homepage: https://github.com/NetEase/Emmagee * Homepage: https://github.com/NetEase/Emmagee
...@@ -16,7 +16,7 @@ Unlike most other performance test tools that only do system-level monitoring, E ...@@ -16,7 +16,7 @@ Unlike most other performance test tools that only do system-level monitoring, E
you should not miss: you should not miss:
* Open source * Open source
* Easy to use * Easy to use
* Process-specific monitoring * Process-specific monitoring, including CPU, memory, network traffic, battery current and status
* Floating window that renders real-time process status * Floating window that renders real-time process status
* CSV format report that can be converted into any other format you want * CSV format report that can be converted into any other format you want
* User-defined collecting interval * User-defined collecting interval
...@@ -32,17 +32,22 @@ build the apk file youself [here](https://github.com/NetEase/Emmagee/wiki/How-to ...@@ -32,17 +32,22 @@ build the apk file youself [here](https://github.com/NetEase/Emmagee/wiki/How-to
3. Select a target process 3. Select a target process
4. Click Start button 4. Click Start button
Meanwhile you'd better follow the rules below And Enjoy!
If you want to stop the test, just go back to Emmagee and click Stop button.
## Coming Soon
* Integrating FPS and starting time
## How to Contribute?
You are welcome to contribute to Emmagee, meanwhile you'd better follow the rules below
* It's *NOT* recommended to submit a pull request directly to Emmagee's `master` branch. `develop` branch is more appropriate * It's *NOT* recommended to submit a pull request directly to Emmagee's `master` branch. `develop` branch is more appropriate
* Follow common Java coding conventions * Follow common Java coding conventions
* Put all Java class files under *com.netease* package * Put all Java class files under *com.netease* package
* Add the following [license](#license) in each Java class file * Add the following [license](#license) in each Java class file
And Enjoy!
If you want to stop the test, just go back to Emmagee and click Stop button.
## Contributors ## Contributors
* NetEase, Inc. * NetEase, Inc.
......
1.1 1.2
\ No newline at end of file \ No newline at end of file
...@@ -65,7 +65,8 @@ ...@@ -65,7 +65,8 @@
android:layout_weight="0.4" android:layout_weight="0.4"
android:gravity="right" android:gravity="right"
android:paddingRight="10.0dip" android:paddingRight="10.0dip"
android:textColor="#FFFFFF" /> android:textColor="#FFFFFF" />
<Button <Button
android:id="@+id/wifi" android:id="@+id/wifi"
android:layout_width="80dp" android:layout_width="80dp"
......
...@@ -72,8 +72,7 @@ import com.netease.qa.emmagee.utils.MyApplication; ...@@ -72,8 +72,7 @@ import com.netease.qa.emmagee.utils.MyApplication;
*/ */
public class EmmageeService extends Service { public class EmmageeService extends Service {
private final static String LOG_TAG = "Emmagee-" private final static String LOG_TAG = "Emmagee-" + EmmageeService.class.getSimpleName();
+ EmmageeService.class.getSimpleName();
private WindowManager windowManager = null; private WindowManager windowManager = null;
private WindowManager.LayoutParams wmParams = null; private WindowManager.LayoutParams wmParams = null;
...@@ -116,6 +115,7 @@ public class EmmageeService extends Service { ...@@ -116,6 +115,7 @@ public class EmmageeService extends Service {
private String temperature; private String temperature;
private String voltage; private String voltage;
private CurrentInfo currentInfo; private CurrentInfo currentInfo;
private BatteryInfoBroadcastReceiver batteryBroadcast = null;
@Override @Override
public void onCreate() { public void onCreate() {
...@@ -129,8 +129,8 @@ public class EmmageeService extends Service { ...@@ -129,8 +129,8 @@ public class EmmageeService extends Service {
fomart.setMinimumFractionDigits(0); fomart.setMinimumFractionDigits(0);
des = new EncryptData("emmagee"); des = new EncryptData("emmagee");
currentInfo = new CurrentInfo(); currentInfo = new CurrentInfo();
registerReceiver(new BatteryInfoBroadcastReceiver(), new IntentFilter( batteryBroadcast = new BatteryInfoBroadcastReceiver();
"android.intent.action.BATTERY_CHANGED")); registerReceiver(batteryBroadcast, new IntentFilter("android.intent.action.BATTERY_CHANGED"));
} }
/** /**
...@@ -150,11 +150,9 @@ public class EmmageeService extends Service { ...@@ -150,11 +150,9 @@ public class EmmageeService extends Service {
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
totalBatt = String.valueOf(level * 100 / scale) + "%"; totalBatt = String.valueOf(level * 100 / scale) + "%";
voltage = String.valueOf(intent.getIntExtra( voltage = String.valueOf(intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1) * 1.0 / 1000);
BatteryManager.EXTRA_VOLTAGE, -1) * 1.0 / 1000);
temperature = String.valueOf(intent.getIntExtra( temperature = String.valueOf(intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1) * 1.0 / 10);
BatteryManager.EXTRA_TEMPERATURE, -1) * 1.0 / 10);
} }
} }
...@@ -164,13 +162,9 @@ public class EmmageeService extends Service { ...@@ -164,13 +162,9 @@ public class EmmageeService extends Service {
@Override @Override
public void onStart(Intent intent, int startId) { public void onStart(Intent intent, int startId) {
Log.i(LOG_TAG, "onStart"); Log.i(LOG_TAG, "onStart");
PendingIntent contentIntent = PendingIntent.getActivity( PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(), 0, new Intent(this, MainPageActivity.class), 0);
getBaseContext(), 0, new Intent(this, MainPageActivity.class), NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
0); builder.setContentIntent(contentIntent).setSmallIcon(R.drawable.icon).setWhen(System.currentTimeMillis()).setAutoCancel(true)
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this);
builder.setContentIntent(contentIntent).setSmallIcon(R.drawable.icon)
.setWhen(System.currentTimeMillis()).setAutoCancel(true)
.setContentTitle("Emmagee"); .setContentTitle("Emmagee");
startForeground(startId, builder.build()); startForeground(startId, builder.build());
...@@ -184,12 +178,9 @@ public class EmmageeService extends Service { ...@@ -184,12 +178,9 @@ public class EmmageeService extends Service {
readSettingInfo(intent); readSettingInfo(intent);
delaytime = Integer.parseInt(time) * 1000; delaytime = Integer.parseInt(time) * 1000;
if (isFloating) { if (isFloating) {
viFloatingWindow = LayoutInflater.from(this).inflate( viFloatingWindow = LayoutInflater.from(this).inflate(R.layout.floating, null);
R.layout.floating, null); txtUnusedMem = (TextView) viFloatingWindow.findViewById(R.id.memunused);
txtUnusedMem = (TextView) viFloatingWindow txtTotalMem = (TextView) viFloatingWindow.findViewById(R.id.memtotal);
.findViewById(R.id.memunused);
txtTotalMem = (TextView) viFloatingWindow
.findViewById(R.id.memtotal);
txtBatt = (TextView) viFloatingWindow.findViewById(R.id.batt); txtBatt = (TextView) viFloatingWindow.findViewById(R.id.batt);
txtTraffic = (TextView) viFloatingWindow.findViewById(R.id.traffic); txtTraffic = (TextView) viFloatingWindow.findViewById(R.id.traffic);
btnWifi = (Button) viFloatingWindow.findViewById(R.id.wifi); btnWifi = (Button) viFloatingWindow.findViewById(R.id.wifi);
...@@ -204,6 +195,7 @@ public class EmmageeService extends Service { ...@@ -204,6 +195,7 @@ public class EmmageeService extends Service {
txtUnusedMem.setTextColor(android.graphics.Color.RED); txtUnusedMem.setTextColor(android.graphics.Color.RED);
txtTotalMem.setTextColor(android.graphics.Color.RED); txtTotalMem.setTextColor(android.graphics.Color.RED);
txtTraffic.setTextColor(android.graphics.Color.RED); txtTraffic.setTextColor(android.graphics.Color.RED);
txtBatt.setTextColor(android.graphics.Color.RED);
imgViIcon = (ImageView) viFloatingWindow.findViewById(R.id.img2); imgViIcon = (ImageView) viFloatingWindow.findViewById(R.id.img2);
imgViIcon.setVisibility(View.GONE); imgViIcon.setVisibility(View.GONE);
createFloatingWindow(); createFloatingWindow();
...@@ -222,9 +214,7 @@ public class EmmageeService extends Service { ...@@ -222,9 +214,7 @@ public class EmmageeService extends Service {
Properties properties = new Properties(); Properties properties = new Properties();
properties.load(new FileInputStream(settingTempFile)); properties.load(new FileInputStream(settingTempFile));
String interval = properties.getProperty("interval").trim(); String interval = properties.getProperty("interval").trim();
isFloating = "true" isFloating = "true".equals(properties.getProperty("isfloat").trim()) ? true : false;
.equals(properties.getProperty("isfloat").trim()) ? true
: false;
sender = properties.getProperty("sender").trim(); sender = properties.getProperty("sender").trim();
password = properties.getProperty("password").trim(); password = properties.getProperty("password").trim();
recipients = properties.getProperty("recipients").trim(); recipients = properties.getProperty("recipients").trim();
...@@ -247,21 +237,14 @@ public class EmmageeService extends Service { ...@@ -247,21 +237,14 @@ public class EmmageeService extends Service {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String mDateTime; String mDateTime;
if ((Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk"))) if ((Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk")))
mDateTime = formatter.format(cal.getTime().getTime() + 8 * 60 * 60 mDateTime = formatter.format(cal.getTime().getTime() + 8 * 60 * 60 * 1000);
* 1000);
else else
mDateTime = formatter.format(cal.getTime().getTime()); mDateTime = formatter.format(cal.getTime().getTime());
if (android.os.Environment.getExternalStorageState().equals( if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
android.os.Environment.MEDIA_MOUNTED)) { resultFilePath = android.os.Environment.getExternalStorageDirectory() + File.separator + "Emmagee_TestResult_" + mDateTime + ".csv";
resultFilePath = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Emmagee_TestResult_" + mDateTime + ".csv";
} else { } else {
resultFilePath = getBaseContext().getFilesDir().getPath() resultFilePath = getBaseContext().getFilesDir().getPath() + File.separator + "Emmagee_TestResult_" + mDateTime + ".csv";
+ File.separator + "Emmagee_TestResult_" + mDateTime
+ ".csv";
} }
try { try {
File resultFile = new File(resultFilePath); File resultFile = new File(resultFilePath);
...@@ -271,17 +254,11 @@ public class EmmageeService extends Service { ...@@ -271,17 +254,11 @@ public class EmmageeService extends Service {
bw = new BufferedWriter(osw); bw = new BufferedWriter(osw);
long totalMemorySize = memoryInfo.getTotalMemory(); long totalMemorySize = memoryInfo.getTotalMemory();
String totalMemory = fomart.format((double) totalMemorySize / 1024); String totalMemory = fomart.format((double) totalMemorySize / 1024);
bw.write("指定应用的CPU内存监控情况\r\n" + "应用包名:," + packageName + "\r\n" bw.write("指定应用的CPU内存监控情况\r\n" + "应用包名:," + packageName + "\r\n" + "应用名称: ," + processName + "\r\n" + "应用PID: ," + pid + "\r\n"
+ "应用名称: ," + processName + "\r\n" + "应用PID: ," + pid + "机器内存大小(MB):," + totalMemory + "MB\r\n" + "机器CPU型号:," + cpuInfo.getCpuName() + "\r\n" + "机器android系统版本:,"
+ "\r\n" + "机器内存大小(MB):," + totalMemory + "MB\r\n" + memoryInfo.getSDKVersion() + "\r\n" + "手机型号:," + memoryInfo.getPhoneType() + "\r\n" + "UID:," + uid + "\r\n");
+ "机器CPU型号:," + cpuInfo.getCpuName() + "\r\n" bw.write("时间" + "," + "应用占用内存PSS(MB)" + "," + "应用占用内存比(%)" + "," + " 机器剩余内存(MB)" + "," + "应用占用CPU率(%)" + "," + "CPU总使用率(%)" + ","
+ "机器android系统版本:," + memoryInfo.getSDKVersion() + "\r\n" + "流量(KB)" + "," + "电量(%)" + "," + "电流(mA)" + "," + "温度(C)" + "," + "电压(V)" + "\r\n");
+ "手机型号:," + memoryInfo.getPhoneType() + "\r\n" + "UID:,"
+ uid + "\r\n");
bw.write("时间" + "," + "应用占用内存PSS(MB)" + "," + "应用占用内存比(%)" + ","
+ " 机器剩余内存(MB)" + "," + "应用占用CPU率(%)" + "," + "CPU总使用率(%)"
+ "," + "流量(KB)" + "," + "电量(%)" + "," + "电流(mA)" + ","
+ "温度(C)" + "," + "电压(V)" + "\r\n");
} catch (IOException e) { } catch (IOException e) {
Log.e(LOG_TAG, e.getMessage()); Log.e(LOG_TAG, e.getMessage());
} }
...@@ -291,13 +268,11 @@ public class EmmageeService extends Service { ...@@ -291,13 +268,11 @@ public class EmmageeService extends Service {
* create a floating window to show real-time data. * create a floating window to show real-time data.
*/ */
private void createFloatingWindow() { private void createFloatingWindow() {
SharedPreferences shared = getSharedPreferences("float_flag", SharedPreferences shared = getSharedPreferences("float_flag", Activity.MODE_PRIVATE);
Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit(); SharedPreferences.Editor editor = shared.edit();
editor.putInt("float", 1); editor.putInt("float", 1);
editor.commit(); editor.commit();
windowManager = (WindowManager) getApplicationContext() windowManager = (WindowManager) getApplicationContext().getSystemService("window");
.getSystemService("window");
wmParams = ((MyApplication) getApplication()).getMywmParams(); wmParams = ((MyApplication) getApplication()).getMywmParams();
wmParams.type = 2002; wmParams.type = 2002;
wmParams.flags |= 8; wmParams.flags |= 8;
...@@ -319,8 +294,7 @@ public class EmmageeService extends Service { ...@@ -319,8 +294,7 @@ public class EmmageeService extends Service {
startY = y; startY = y;
mTouchStartX = event.getX(); mTouchStartX = event.getX();
mTouchStartY = event.getY(); mTouchStartY = event.getY();
Log.d("startP", "startX" + mTouchStartX + "====startY" Log.d("startP", "startX" + mTouchStartX + "====startY" + mTouchStartY);
+ mTouchStartY);
break; break;
case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_MOVE:
// state = MotionEvent.ACTION_MOVE; // state = MotionEvent.ACTION_MOVE;
...@@ -344,8 +318,7 @@ public class EmmageeService extends Service { ...@@ -344,8 +318,7 @@ public class EmmageeService extends Service {
try { try {
btnWifi = (Button) viFloatingWindow.findViewById(R.id.wifi); btnWifi = (Button) viFloatingWindow.findViewById(R.id.wifi);
String buttonText = (String) btnWifi.getText(); String buttonText = (String) btnWifi.getText();
String wifiText = getResources().getString( String wifiText = getResources().getString(R.string.openwifi);
R.string.openwifi);
if (buttonText.equals(wifiText)) { if (buttonText.equals(wifiText)) {
wifiManager.setWifiEnabled(true); wifiManager.setWifiEnabled(true);
btnWifi.setText(R.string.closewifi); btnWifi.setText(R.string.closewifi);
...@@ -354,8 +327,7 @@ public class EmmageeService extends Service { ...@@ -354,8 +327,7 @@ public class EmmageeService extends Service {
btnWifi.setText(R.string.openwifi); btnWifi.setText(R.string.openwifi);
} }
} catch (Exception e) { } catch (Exception e) {
Toast.makeText(viFloatingWindow.getContext(), "操作wifi失败", Toast.makeText(viFloatingWindow.getContext(), "操作wifi失败", Toast.LENGTH_LONG).show();
Toast.LENGTH_LONG).show();
Log.e(LOG_TAG, e.toString()); Log.e(LOG_TAG, e.toString());
} }
} }
...@@ -366,8 +338,7 @@ public class EmmageeService extends Service { ...@@ -366,8 +338,7 @@ public class EmmageeService extends Service {
* show the image. * show the image.
*/ */
private void showImg() { private void showImg() {
if (Math.abs(x - startX) < 1.5 && Math.abs(y - startY) < 1.5 if (Math.abs(x - startX) < 1.5 && Math.abs(y - startY) < 1.5 && !imgViIcon.isShown()) {
&& !imgViIcon.isShown()) {
imgViIcon.setVisibility(View.VISIBLE); imgViIcon.setVisibility(View.VISIBLE);
} else if (imgViIcon.isShown()) { } else if (imgViIcon.isShown()) {
imgViIcon.setVisibility(View.GONE); imgViIcon.setVisibility(View.GONE);
...@@ -404,9 +375,8 @@ public class EmmageeService extends Service { ...@@ -404,9 +375,8 @@ public class EmmageeService extends Service {
long freeMemory = memoryInfo.getFreeMemorySize(getBaseContext()); long freeMemory = memoryInfo.getFreeMemorySize(getBaseContext());
String freeMemoryKb = fomart.format((double) freeMemory / 1024); String freeMemoryKb = fomart.format((double) freeMemory / 1024);
String processMemory = fomart.format((double) pidMemory / 1024); String processMemory = fomart.format((double) pidMemory / 1024);
String currentBatt = String.valueOf(currentInfo.getValue()); String currentBatt = String.valueOf(currentInfo.getCurrentValue());
ArrayList<String> processInfo = cpuInfo.getCpuRatioInfo(totalBatt, ArrayList<String> processInfo = cpuInfo.getCpuRatioInfo(totalBatt, currentBatt, temperature, voltage);
currentBatt, temperature, voltage);
if (isFloating) { if (isFloating) {
String processCpuRatio = "0"; String processCpuRatio = "0";
String totalCpuRatio = "0"; String totalCpuRatio = "0";
...@@ -432,16 +402,13 @@ public class EmmageeService extends Service { ...@@ -432,16 +402,13 @@ public class EmmageeService extends Service {
return; return;
} }
if (processCpuRatio != null && totalCpuRatio != null) { if (processCpuRatio != null && totalCpuRatio != null) {
txtUnusedMem.setText("占用内存:" + processMemory + "MB" + ",机器剩余:" txtUnusedMem.setText("占用内存:" + processMemory + "MB" + ",机器剩余:" + freeMemoryKb + "MB");
+ freeMemoryKb + "MB"); txtTotalMem.setText("占用CPU:" + processCpuRatio + "%" + ",总体CPU:" + totalCpuRatio + "%");
txtTotalMem.setText("占用CPU:" + processCpuRatio + "%"
+ ",总体CPU:" + totalCpuRatio + "%");
txtBatt.setText("电量:" + totalBatt + ",电流:" + currentBatt + "mA"); txtBatt.setText("电量:" + totalBatt + ",电流:" + currentBatt + "mA");
if ("-1".equals(trafficSize)) { if ("-1".equals(trafficSize)) {
txtTraffic.setText("本程序或本设备不支持流量统计"); txtTraffic.setText("本程序或本设备不支持流量统计");
} else if (isMb) } else if (isMb)
txtTraffic.setText("消耗流量:" + fomart.format(trafficMb) txtTraffic.setText("消耗流量:" + fomart.format(trafficMb) + "MB");
+ "MB");
else else
txtTraffic.setText("消耗流量:" + trafficSize + "KB"); txtTraffic.setText("消耗流量:" + trafficSize + "KB");
} }
...@@ -481,22 +448,18 @@ public class EmmageeService extends Service { ...@@ -481,22 +448,18 @@ public class EmmageeService extends Service {
handler.removeCallbacks(task); handler.removeCallbacks(task);
closeOpenedStream(); closeOpenedStream();
isStop = true; isStop = true;
unregisterReceiver(batteryBroadcast);
boolean isSendSuccessfully = false; boolean isSendSuccessfully = false;
try { try {
isSendSuccessfully = MailSender.sendTextMail(sender, isSendSuccessfully = MailSender.sendTextMail(sender, des.decrypt(password), smtp, "Emmagee Performance Test Report", "see attachment",
des.decrypt(password), smtp,
"Emmagee Performance Test Report", "see attachment",
resultFilePath, receivers); resultFilePath, receivers);
} catch (Exception e) { } catch (Exception e) {
isSendSuccessfully = false; isSendSuccessfully = false;
} }
if (isSendSuccessfully) { if (isSendSuccessfully) {
Toast.makeText(this, "测试结果报表已发送至邮箱:" + recipients, Toast.makeText(this, "测试结果报表已发送至邮箱:" + recipients, Toast.LENGTH_LONG).show();
Toast.LENGTH_LONG).show();
} else { } else {
Toast.makeText(this, Toast.makeText(this, "测试结果未成功发送至邮箱,结果保存在:" + EmmageeService.resultFilePath, Toast.LENGTH_LONG).show();
"测试结果未成功发送至邮箱,结果保存在:" + EmmageeService.resultFilePath,
Toast.LENGTH_LONG).show();
} }
super.onDestroy(); super.onDestroy();
stopForeground(true); stopForeground(true);
......
...@@ -213,122 +213,5 @@ public class CpuInfo { ...@@ -213,122 +213,5 @@ public class CpuInfo {
// PttService.closeOpenedStream() // PttService.closeOpenedStream()
} }
return cpuUsedRatio; return cpuUsedRatio;
} }
// // TODO coming soon
// public String cpuinfo() {
// String sys_info = "";
// String s;
// try {
// RandomAccessFile reader_stat = new RandomAccessFile("/proc/stat",
// "r");
// RandomAccessFile reader_info = new RandomAccessFile(
// "/proc/cpuinfo", "r");
// sys_info = reader_info.readLine(); // CPU型号
// String load_info;
// String cpu_stat = reader_stat.readLine(); // cpu行信息
// String cpu0_stat = reader_stat.readLine(); // cpu0
// String cpu1_stat = reader_stat.readLine(); // cpu1
//
// String[] tok = cpu_stat.split(" ");
// String[] tok1 = cpu0_stat.split(" ");
// String[] tok2 = cpu1_stat.split(" ");
//
// // 判断单核
// if (tok[2].equals(tok1[1])) {
// long idle_s1 = Long.parseLong(tok[5]);
// long cpu_s1 = Long.parseLong(tok[2]) + Long.parseLong(tok[3])
// + Long.parseLong(tok[4]) + Long.parseLong(tok[6])
// + Long.parseLong(tok[5]) + Long.parseLong(tok[7])
// + Long.parseLong(tok[8]);
//
// try {
// Thread.sleep(1000);
//
// } catch (Exception e) {
// }
//
// reader_stat.seek(0);
//
// load_info = reader_stat.readLine();
//
// reader_stat.close();
//
// tok = load_info.split(" ");
// long idle_s2 = Long.parseLong(tok[5]);
//
// long cpu_s2 = Long.parseLong(tok[2]) + Long.parseLong(tok[3])
// + Long.parseLong(tok[4]) + Long.parseLong(tok[6])
// + Long.parseLong(tok[5]) + Long.parseLong(tok[7])
// + Long.parseLong(tok[8]);
//
// return "CPU使用率为:"
// + (100 * ((cpu_s2 - idle_s2) - (cpu_s1 - idle_s1)) / (cpu_s2 - cpu_s1))
// + "%";
//
// }
//
// // 双核情况
// else if (tok2[0].equals("cpu1")) {
// // 双核
// reader_stat = new RandomAccessFile("/proc/stat", "r");
// long[] idle_d1 = null;
// long[] cpu_d1 = null;
// long[] idle_d2 = null;
// long[] cpu_d2 = null;
// idle_d1[0] = Long.parseLong(tok1[4]); // cpu0空闲时间
// cpu_d1[0] = Long.parseLong(tok1[2]) + Long.parseLong(tok1[3])
// + Long.parseLong(tok1[4]) + Long.parseLong(tok1[6])
// + Long.parseLong(tok1[5]) + Long.parseLong(tok1[7])
// + Long.parseLong(tok1[1]); // cpu0非空闲时间
// idle_d1[1] = Long.parseLong(tok2[4]);
// cpu_d1[1] = Long.parseLong(tok2[2]) + Long.parseLong(tok2[3])
// + Long.parseLong(tok2[4]) + Long.parseLong(tok2[6])
// + Long.parseLong(tok2[5]) + Long.parseLong(tok2[7])
// + Long.parseLong(tok2[1]);
//
// try {
// Thread.sleep(1000);
//
// } catch (Exception e) {
// }
//
// reader_stat.seek(0);
//
// cpu_stat = reader_stat.readLine(); // cpu行信息
// cpu0_stat = reader_stat.readLine(); // cpu0
// cpu1_stat = reader_stat.readLine();
//
// tok1 = cpu0_stat.split(" ");
// tok2 = cpu1_stat.split(" ");
//
// idle_d2[0] = Long.parseLong(tok1[4]); // cpu0空闲时间
// cpu_d2[0] = Long.parseLong(tok1[2]) + Long.parseLong(tok1[3])
// + Long.parseLong(tok1[4]) + Long.parseLong(tok1[6])
// + Long.parseLong(tok1[5]) + Long.parseLong(tok1[7])
// + Long.parseLong(tok1[1]); // cpu0非空闲时间
// idle_d2[1] = Long.parseLong(tok2[4]);
// cpu_d2[1] = Long.parseLong(tok2[2]) + Long.parseLong(tok2[3])
// + Long.parseLong(tok2[4]) + Long.parseLong(tok2[6])
// + Long.parseLong(tok2[5]) + Long.parseLong(tok2[7])
// + Long.parseLong(tok2[1]);
//
// reader_stat.close();
// return "CPU1使用率为:"
// + (100 * ((cpu_d2[0] - idle_d2[0]) - (cpu_d1[0] - idle_d1[0])) /
// (cpu_d2[0] - cpu_d1[0]))
// + "%"
// + "\n"
// + "CPU2使用率为:"
// + (100 * ((cpu_d2[1] - idle_d2[1]) - (cpu_d1[1] - idle_d1[1])) /
// (cpu_d2[1] - cpu_d1[1]))
// + "%";
// }
// } catch (IOException ex) {
// Log.e(LOG_TAG, ex.getMessage());
//
// }
// return "0";
// }
} }
...@@ -5,6 +5,7 @@ import java.io.DataInputStream; ...@@ -5,6 +5,7 @@ import java.io.DataInputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileReader; import java.io.FileReader;
import java.util.Locale;
import android.os.Build; import android.os.Build;
import android.util.Log; import android.util.Log;
...@@ -17,133 +18,112 @@ import android.util.Log; ...@@ -17,133 +18,112 @@ import android.util.Log;
*/ */
public class CurrentInfo { public class CurrentInfo {
private static final String LOG_TAG = "Emmagee-CurrentInfo"; private static final String LOG_TAG = "Emmagee-CurrentInfo";
private static final String BUILD_MODEL = Build.MODEL.toLowerCase(Locale.ENGLISH);
private static final String I_MBAT = "I_MBAT: ";
private static final String CURRENT_NOW = "/sys/class/power_supply/battery/current_now";
private static final String BATT_CURRENT = "/sys/class/power_supply/battery/batt_current";
private static final String SMEM_TEXT = "/sys/class/power_supply/battery/smem_text";
private static final String BATT_CURRENT_ADC = "/sys/class/power_supply/battery/batt_current_adc";
private static final String CURRENT_AVG = "/sys/class/power_supply/battery/current_avg";
public Long getValue() { public Long getCurrentValue() {
File f = null; File f = null;
// htc desire hd / desire z? Log.d(LOG_TAG, BUILD_MODEL);
if (Build.MODEL.toLowerCase().contains("desire hd") // galaxy s4,oppo find,samgsung note2
|| Build.MODEL.toLowerCase().contains("desire z")) { if (BUILD_MODEL.contains("sgh-i337") || BUILD_MODEL.contains("gt-i9505") || BUILD_MODEL.contains("sch-i545")
f = new File("/sys/class/power_supply/battery/batt_current"); || BUILD_MODEL.contains("find 5") || BUILD_MODEL.contains("sgh-m919") || BUILD_MODEL.contains("sgh-i537")
|| BUILD_MODEL.contains("x907") || BUILD_MODEL.contains("gt-n7100")) {
f = new File(CURRENT_NOW);
if (f.exists()) {
return getCurrentValue(f, false);
}
}
// samsung galaxy
if (BUILD_MODEL.contains("gt-p31") || BUILD_MODEL.contains("gt-p51")) {
f = new File(CURRENT_AVG);
if (f.exists()) {
return getCurrentValue(f, false);
}
}
// htc desire hd ,desire z
if (BUILD_MODEL.contains("desire hd") || BUILD_MODEL.contains("desire z")) {
f = new File(BATT_CURRENT);
if (f.exists()) if (f.exists())
return getCurrentValue(f, false); return getCurrentValue(f, false);
} }
// sony ericsson xperia x1 // htc sensation z710e
f = new File( f = new File(BATT_CURRENT);
"/sys/devices/platform/i2c-adapter/i2c-0/0-0036/power_supply/ds2746-battery/current_now");
if (f.exists())
return getCurrentValue(f, false);
// xdandroid
/* if (Build.MODEL.equalsIgnoreCase("MSM")) { */
f = new File(
"/sys/devices/platform/i2c-adapter/i2c-0/0-0036/power_supply/battery/current_now");
if (f.exists()) if (f.exists())
return getCurrentValue(f, false); return getCurrentValue(f, false);
/* } */
// droid eris // htc one V
f = new File("/sys/class/power_supply/battery/smem_text"); f = new File(SMEM_TEXT);
if (f.exists()) if (f.exists())
return getSMemValue(); return getSMemValue();
// some htc devices
f = new File("/sys/class/power_supply/battery/batt_current"); // nexus one,meizu
if (f.exists()) f = new File(CURRENT_NOW);
return getCurrentValue(f, false);
// nexus one
f = new File("/sys/class/power_supply/battery/current_now");
if (f.exists()) if (f.exists())
return getCurrentValue(f, true); return getCurrentValue(f, true);
// samsung galaxy vibrant
f = new File("/sys/class/power_supply/battery/batt_chg_current"); // galaxy note, galaxy s2
f = new File(BATT_CURRENT_ADC);
if (f.exists()) if (f.exists())
return getCurrentValue(f, false); return getCurrentValue(f, false);
// sony ericsson x10
f = new File("/sys/class/power_supply/battery/charger_current"); // acer V360
f = new File("/sys/class/power_supply/battery/BatteryAverageCurrent");
if (f.exists()) if (f.exists())
return getCurrentValue(f, false); return getCurrentValue(f, false);
// moto milestone,moto mb526
f = new File("/sys/devices/platform/cpcap_battery/power_supply/usb/current_now");
if (f.exists())
return getCurrentValue(f, false);
return null; return null;
} }
public static Long getSMemValue() { /**
* 从smem_text文件中读取电流数据
*
* @return
*/
public Long getSMemValue() {
boolean success = false; boolean success = false;
String text = null; String text = null;
Long value = null;
try { try {
FileReader fr = new FileReader( FileReader fr = new FileReader(SMEM_TEXT);
"/sys/class/power_supply/battery/smem_text");
BufferedReader br = new BufferedReader(fr); BufferedReader br = new BufferedReader(fr);
String line = br.readLine(); String line = br.readLine();
while (line != null) { while (line != null) {
if (line.contains("I_MBAT")) { if (line.contains(I_MBAT)) {
text = line.substring(line.indexOf("I_MBAT: ") + 8); text = line.substring(line.indexOf(I_MBAT) + 8);
success = true; success = true;
break; break;
} }
line = br.readLine(); line = br.readLine();
} }
br.close();
fr.close(); fr.close();
} catch (Exception ex) { br.close();
Log.e(LOG_TAG, ex.getMessage()); } catch (Exception e) {
ex.printStackTrace(); e.printStackTrace();
} }
Long value = null;
if (success) { if (success) {
try { try {
value = Long.parseLong(text); value = Long.parseLong(text);
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
Log.e(LOG_TAG, nfe.getMessage()); nfe.printStackTrace();
value = null; value = null;
} }
} }
return value; return value;
} }
public static Long getBattAttrValue(File f, String dischargeField,
String chargeField) {
String text = null;
Long value = null;
try {
// @@@ debug
// StringReader fr = new
// StringReader("vref: 1248\r\nbatt_id: 3\r\nbatt_vol: 4068\r\nbatt_current: 0\r\nbatt_discharge_current: 123\r\nbatt_temperature: 329\r\nbatt_temp_protection:normal\r\nPd_M:0\r\nI_MBAT:-313\r\npercent_last(RP): 94\r\npercent_update: 71\r\nlevel: 71\r\nfirst_level: 100\r\nfull_level:100\r\ncapacity:1580\r\ncharging_source: USB\r\ncharging_enabled: Slow\r\n");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
final String chargeFieldHead = chargeField + ": ";
final String dischargeFieldHead = dischargeField + ": ";
while (line != null) {
if (line.contains(chargeField)) {
text = line.substring(line.indexOf(chargeFieldHead)
+ chargeFieldHead.length());
try {
value = Long.parseLong(text);
if (value != 0)
break;
} catch (NumberFormatException nfe) {
Log.e(LOG_TAG, nfe.getMessage(), nfe);
}
}
// "batt_discharge_current:"
if (line.contains(dischargeField)) {
text = line.substring(line.indexOf(dischargeFieldHead)
+ dischargeFieldHead.length());
try {
value = (-1) * Math.abs(Long.parseLong(text));
} catch (NumberFormatException nfe) {
Log.e(LOG_TAG, nfe.getMessage(), nfe);
}
break;
}
line = br.readLine();
}
br.close();
fr.close();
} catch (Exception ex) {
Log.e(LOG_TAG, ex.getMessage(), ex);
}
return value;
}
/** /**
* 获取当前的电流值 * 获取当前的电流值
* *
...@@ -152,28 +132,35 @@ public class CurrentInfo { ...@@ -152,28 +132,35 @@ public class CurrentInfo {
* @return * @return
*/ */
public Long getCurrentValue(File file, boolean convertToMillis) { public Long getCurrentValue(File file, boolean convertToMillis) {
String text = null; Log.d(LOG_TAG, "*** getCurrentValue ***");
Log.d(LOG_TAG, "*** " + convertToMillis + " ***");
String line = null;
Long value = null;
FileInputStream fs = null;
DataInputStream ds = null;
try { try {
FileInputStream fs = new FileInputStream(file); fs = new FileInputStream(file);
DataInputStream ds = new DataInputStream(fs); ds = new DataInputStream(fs);
text = ds.readLine(); line = ds.readLine();
ds.close(); } catch (Exception e) {
fs.close(); e.printStackTrace();
} catch (Exception ex) { } finally {
ex.printStackTrace(); try {
fs.close();
ds.close();
} catch (Exception ex) {
ex.printStackTrace();
}
} }
Long value = null; if (line != null) {
if (text != null) {
try { try {
value = Long.parseLong(text); value = Long.parseLong(line);
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
value = null; value = null;
} }
if (convertToMillis) if (convertToMillis)
value = value / 1000; // convert to milliampere value = value / 1000;
} }
return value; return value;
} }
} }
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册