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

new features:add battery monitoring and quad-core CPU

上级 d4ec6c24
......@@ -7,5 +7,6 @@
<classpathentry kind="lib" path="libs/activation.jar"/>
<classpathentry kind="lib" path="libs/mail.jar"/>
<classpathentry kind="lib" path="libs/additionnal.jar"/>
<classpathentry kind="lib" path="libs/android-support-v4.jar"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
##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
network traffic. Additionally, it also provides several cool features such as customizing interval of collecting data,
Emmagee is a practical, handy performance test tool for specified Android App, which can monitor CPU, memory,
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.
* Homepage: https://github.com/NetEase/Emmagee
......@@ -16,7 +16,7 @@ Unlike most other performance test tools that only do system-level monitoring, E
you should not miss:
* Open source
* 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
* CSV format report that can be converted into any other format you want
* User-defined collecting interval
......@@ -32,17 +32,22 @@ build the apk file youself [here](https://github.com/NetEase/Emmagee/wiki/How-to
3. Select a target process
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
* Follow common Java coding conventions
* Put all Java class files under *com.netease* package
* 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
* NetEase, Inc.
......
1.1
\ No newline at end of file
1.2
\ No newline at end of file
......@@ -65,7 +65,8 @@
android:layout_weight="0.4"
android:gravity="right"
android:paddingRight="10.0dip"
android:textColor="#FFFFFF" />
android:textColor="#FFFFFF" />
<Button
android:id="@+id/wifi"
android:layout_width="80dp"
......
......@@ -72,8 +72,7 @@ import com.netease.qa.emmagee.utils.MyApplication;
*/
public class EmmageeService extends Service {
private final static String LOG_TAG = "Emmagee-"
+ EmmageeService.class.getSimpleName();
private final static String LOG_TAG = "Emmagee-" + EmmageeService.class.getSimpleName();
private WindowManager windowManager = null;
private WindowManager.LayoutParams wmParams = null;
......@@ -116,6 +115,7 @@ public class EmmageeService extends Service {
private String temperature;
private String voltage;
private CurrentInfo currentInfo;
private BatteryInfoBroadcastReceiver batteryBroadcast = null;
@Override
public void onCreate() {
......@@ -129,8 +129,8 @@ public class EmmageeService extends Service {
fomart.setMinimumFractionDigits(0);
des = new EncryptData("emmagee");
currentInfo = new CurrentInfo();
registerReceiver(new BatteryInfoBroadcastReceiver(), new IntentFilter(
"android.intent.action.BATTERY_CHANGED"));
batteryBroadcast = new BatteryInfoBroadcastReceiver();
registerReceiver(batteryBroadcast, new IntentFilter("android.intent.action.BATTERY_CHANGED"));
}
/**
......@@ -150,11 +150,9 @@ public class EmmageeService extends Service {
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
totalBatt = String.valueOf(level * 100 / scale) + "%";
voltage = String.valueOf(intent.getIntExtra(
BatteryManager.EXTRA_VOLTAGE, -1) * 1.0 / 1000);
voltage = String.valueOf(intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1) * 1.0 / 1000);
temperature = String.valueOf(intent.getIntExtra(
BatteryManager.EXTRA_TEMPERATURE, -1) * 1.0 / 10);
temperature = String.valueOf(intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1) * 1.0 / 10);
}
}
......@@ -164,13 +162,9 @@ public class EmmageeService extends Service {
@Override
public void onStart(Intent intent, int startId) {
Log.i(LOG_TAG, "onStart");
PendingIntent contentIntent = PendingIntent.getActivity(
getBaseContext(), 0, new Intent(this, MainPageActivity.class),
0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this);
builder.setContentIntent(contentIntent).setSmallIcon(R.drawable.icon)
.setWhen(System.currentTimeMillis()).setAutoCancel(true)
PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(), 0, new Intent(this, MainPageActivity.class), 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(contentIntent).setSmallIcon(R.drawable.icon).setWhen(System.currentTimeMillis()).setAutoCancel(true)
.setContentTitle("Emmagee");
startForeground(startId, builder.build());
......@@ -184,12 +178,9 @@ public class EmmageeService extends Service {
readSettingInfo(intent);
delaytime = Integer.parseInt(time) * 1000;
if (isFloating) {
viFloatingWindow = LayoutInflater.from(this).inflate(
R.layout.floating, null);
txtUnusedMem = (TextView) viFloatingWindow
.findViewById(R.id.memunused);
txtTotalMem = (TextView) viFloatingWindow
.findViewById(R.id.memtotal);
viFloatingWindow = LayoutInflater.from(this).inflate(R.layout.floating, null);
txtUnusedMem = (TextView) viFloatingWindow.findViewById(R.id.memunused);
txtTotalMem = (TextView) viFloatingWindow.findViewById(R.id.memtotal);
txtBatt = (TextView) viFloatingWindow.findViewById(R.id.batt);
txtTraffic = (TextView) viFloatingWindow.findViewById(R.id.traffic);
btnWifi = (Button) viFloatingWindow.findViewById(R.id.wifi);
......@@ -204,6 +195,7 @@ public class EmmageeService extends Service {
txtUnusedMem.setTextColor(android.graphics.Color.RED);
txtTotalMem.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.setVisibility(View.GONE);
createFloatingWindow();
......@@ -222,9 +214,7 @@ public class EmmageeService extends Service {
Properties properties = new Properties();
properties.load(new FileInputStream(settingTempFile));
String interval = properties.getProperty("interval").trim();
isFloating = "true"
.equals(properties.getProperty("isfloat").trim()) ? true
: false;
isFloating = "true".equals(properties.getProperty("isfloat").trim()) ? true : false;
sender = properties.getProperty("sender").trim();
password = properties.getProperty("password").trim();
recipients = properties.getProperty("recipients").trim();
......@@ -247,21 +237,14 @@ public class EmmageeService extends Service {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String mDateTime;
if ((Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk")))
mDateTime = formatter.format(cal.getTime().getTime() + 8 * 60 * 60
* 1000);
mDateTime = formatter.format(cal.getTime().getTime() + 8 * 60 * 60 * 1000);
else
mDateTime = formatter.format(cal.getTime().getTime());
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
resultFilePath = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Emmagee_TestResult_" + mDateTime + ".csv";
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
resultFilePath = android.os.Environment.getExternalStorageDirectory() + File.separator + "Emmagee_TestResult_" + mDateTime + ".csv";
} else {
resultFilePath = getBaseContext().getFilesDir().getPath()
+ File.separator + "Emmagee_TestResult_" + mDateTime
+ ".csv";
resultFilePath = getBaseContext().getFilesDir().getPath() + File.separator + "Emmagee_TestResult_" + mDateTime + ".csv";
}
try {
File resultFile = new File(resultFilePath);
......@@ -271,17 +254,11 @@ public class EmmageeService extends Service {
bw = new BufferedWriter(osw);
long totalMemorySize = memoryInfo.getTotalMemory();
String totalMemory = fomart.format((double) totalMemorySize / 1024);
bw.write("指定应用的CPU内存监控情况\r\n" + "应用包名:," + packageName + "\r\n"
+ "应用名称: ," + processName + "\r\n" + "应用PID: ," + pid
+ "\r\n" + "机器内存大小(MB):," + totalMemory + "MB\r\n"
+ "机器CPU型号:," + cpuInfo.getCpuName() + "\r\n"
+ "机器android系统版本:," + memoryInfo.getSDKVersion() + "\r\n"
+ "手机型号:," + memoryInfo.getPhoneType() + "\r\n" + "UID:,"
+ uid + "\r\n");
bw.write("时间" + "," + "应用占用内存PSS(MB)" + "," + "应用占用内存比(%)" + ","
+ " 机器剩余内存(MB)" + "," + "应用占用CPU率(%)" + "," + "CPU总使用率(%)"
+ "," + "流量(KB)" + "," + "电量(%)" + "," + "电流(mA)" + ","
+ "温度(C)" + "," + "电压(V)" + "\r\n");
bw.write("指定应用的CPU内存监控情况\r\n" + "应用包名:," + packageName + "\r\n" + "应用名称: ," + processName + "\r\n" + "应用PID: ," + pid + "\r\n"
+ "机器内存大小(MB):," + totalMemory + "MB\r\n" + "机器CPU型号:," + cpuInfo.getCpuName() + "\r\n" + "机器android系统版本:,"
+ memoryInfo.getSDKVersion() + "\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) {
Log.e(LOG_TAG, e.getMessage());
}
......@@ -291,13 +268,11 @@ public class EmmageeService extends Service {
* create a floating window to show real-time data.
*/
private void createFloatingWindow() {
SharedPreferences shared = getSharedPreferences("float_flag",
Activity.MODE_PRIVATE);
SharedPreferences shared = getSharedPreferences("float_flag", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putInt("float", 1);
editor.commit();
windowManager = (WindowManager) getApplicationContext()
.getSystemService("window");
windowManager = (WindowManager) getApplicationContext().getSystemService("window");
wmParams = ((MyApplication) getApplication()).getMywmParams();
wmParams.type = 2002;
wmParams.flags |= 8;
......@@ -319,8 +294,7 @@ public class EmmageeService extends Service {
startY = y;
mTouchStartX = event.getX();
mTouchStartY = event.getY();
Log.d("startP", "startX" + mTouchStartX + "====startY"
+ mTouchStartY);
Log.d("startP", "startX" + mTouchStartX + "====startY" + mTouchStartY);
break;
case MotionEvent.ACTION_MOVE:
// state = MotionEvent.ACTION_MOVE;
......@@ -344,8 +318,7 @@ public class EmmageeService extends Service {
try {
btnWifi = (Button) viFloatingWindow.findViewById(R.id.wifi);
String buttonText = (String) btnWifi.getText();
String wifiText = getResources().getString(
R.string.openwifi);
String wifiText = getResources().getString(R.string.openwifi);
if (buttonText.equals(wifiText)) {
wifiManager.setWifiEnabled(true);
btnWifi.setText(R.string.closewifi);
......@@ -354,8 +327,7 @@ public class EmmageeService extends Service {
btnWifi.setText(R.string.openwifi);
}
} catch (Exception e) {
Toast.makeText(viFloatingWindow.getContext(), "操作wifi失败",
Toast.LENGTH_LONG).show();
Toast.makeText(viFloatingWindow.getContext(), "操作wifi失败", Toast.LENGTH_LONG).show();
Log.e(LOG_TAG, e.toString());
}
}
......@@ -366,8 +338,7 @@ public class EmmageeService extends Service {
* show the image.
*/
private void showImg() {
if (Math.abs(x - startX) < 1.5 && Math.abs(y - startY) < 1.5
&& !imgViIcon.isShown()) {
if (Math.abs(x - startX) < 1.5 && Math.abs(y - startY) < 1.5 && !imgViIcon.isShown()) {
imgViIcon.setVisibility(View.VISIBLE);
} else if (imgViIcon.isShown()) {
imgViIcon.setVisibility(View.GONE);
......@@ -404,9 +375,8 @@ public class EmmageeService extends Service {
long freeMemory = memoryInfo.getFreeMemorySize(getBaseContext());
String freeMemoryKb = fomart.format((double) freeMemory / 1024);
String processMemory = fomart.format((double) pidMemory / 1024);
String currentBatt = String.valueOf(currentInfo.getValue());
ArrayList<String> processInfo = cpuInfo.getCpuRatioInfo(totalBatt,
currentBatt, temperature, voltage);
String currentBatt = String.valueOf(currentInfo.getCurrentValue());
ArrayList<String> processInfo = cpuInfo.getCpuRatioInfo(totalBatt, currentBatt, temperature, voltage);
if (isFloating) {
String processCpuRatio = "0";
String totalCpuRatio = "0";
......@@ -432,16 +402,13 @@ public class EmmageeService extends Service {
return;
}
if (processCpuRatio != null && totalCpuRatio != null) {
txtUnusedMem.setText("占用内存:" + processMemory + "MB" + ",机器剩余:"
+ freeMemoryKb + "MB");
txtTotalMem.setText("占用CPU:" + processCpuRatio + "%"
+ ",总体CPU:" + totalCpuRatio + "%");
txtUnusedMem.setText("占用内存:" + processMemory + "MB" + ",机器剩余:" + freeMemoryKb + "MB");
txtTotalMem.setText("占用CPU:" + processCpuRatio + "%" + ",总体CPU:" + totalCpuRatio + "%");
txtBatt.setText("电量:" + totalBatt + ",电流:" + currentBatt + "mA");
if ("-1".equals(trafficSize)) {
txtTraffic.setText("本程序或本设备不支持流量统计");
} else if (isMb)
txtTraffic.setText("消耗流量:" + fomart.format(trafficMb)
+ "MB");
txtTraffic.setText("消耗流量:" + fomart.format(trafficMb) + "MB");
else
txtTraffic.setText("消耗流量:" + trafficSize + "KB");
}
......@@ -481,22 +448,18 @@ public class EmmageeService extends Service {
handler.removeCallbacks(task);
closeOpenedStream();
isStop = true;
unregisterReceiver(batteryBroadcast);
boolean isSendSuccessfully = false;
try {
isSendSuccessfully = MailSender.sendTextMail(sender,
des.decrypt(password), smtp,
"Emmagee Performance Test Report", "see attachment",
isSendSuccessfully = MailSender.sendTextMail(sender, des.decrypt(password), smtp, "Emmagee Performance Test Report", "see attachment",
resultFilePath, receivers);
} catch (Exception e) {
isSendSuccessfully = false;
}
if (isSendSuccessfully) {
Toast.makeText(this, "测试结果报表已发送至邮箱:" + recipients,
Toast.LENGTH_LONG).show();
Toast.makeText(this, "测试结果报表已发送至邮箱:" + recipients, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this,
"测试结果未成功发送至邮箱,结果保存在:" + EmmageeService.resultFilePath,
Toast.LENGTH_LONG).show();
Toast.makeText(this, "测试结果未成功发送至邮箱,结果保存在:" + EmmageeService.resultFilePath, Toast.LENGTH_LONG).show();
}
super.onDestroy();
stopForeground(true);
......
......@@ -213,122 +213,5 @@ public class CpuInfo {
// PttService.closeOpenedStream()
}
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;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.util.Locale;
import android.os.Build;
import android.util.Log;
......@@ -17,133 +18,112 @@ import android.util.Log;
*/
public class 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;
// htc desire hd / desire z?
if (Build.MODEL.toLowerCase().contains("desire hd")
|| Build.MODEL.toLowerCase().contains("desire z")) {
f = new File("/sys/class/power_supply/battery/batt_current");
Log.d(LOG_TAG, BUILD_MODEL);
// galaxy s4,oppo find,samgsung note2
if (BUILD_MODEL.contains("sgh-i337") || BUILD_MODEL.contains("gt-i9505") || BUILD_MODEL.contains("sch-i545")
|| 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())
return getCurrentValue(f, false);
}
// sony ericsson xperia x1
f = new File(
"/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");
// htc sensation z710e
f = new File(BATT_CURRENT);
if (f.exists())
return getCurrentValue(f, false);
/* } */
// droid eris
f = new File("/sys/class/power_supply/battery/smem_text");
// htc one V
f = new File(SMEM_TEXT);
if (f.exists())
return getSMemValue();
// some htc devices
f = new File("/sys/class/power_supply/battery/batt_current");
if (f.exists())
return getCurrentValue(f, false);
// nexus one
f = new File("/sys/class/power_supply/battery/current_now");
// nexus one,meizu
f = new File(CURRENT_NOW);
if (f.exists())
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())
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())
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;
}
public static Long getSMemValue() {
/**
* 从smem_text文件中读取电流数据
*
* @return
*/
public Long getSMemValue() {
boolean success = false;
String text = null;
Long value = null;
try {
FileReader fr = new FileReader(
"/sys/class/power_supply/battery/smem_text");
FileReader fr = new FileReader(SMEM_TEXT);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
if (line.contains("I_MBAT")) {
text = line.substring(line.indexOf("I_MBAT: ") + 8);
if (line.contains(I_MBAT)) {
text = line.substring(line.indexOf(I_MBAT) + 8);
success = true;
break;
}
line = br.readLine();
}
br.close();
fr.close();
} catch (Exception ex) {
Log.e(LOG_TAG, ex.getMessage());
ex.printStackTrace();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
Long value = null;
if (success) {
try {
value = Long.parseLong(text);
} catch (NumberFormatException nfe) {
Log.e(LOG_TAG, nfe.getMessage());
nfe.printStackTrace();
value = null;
}
}
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 {
* @return
*/
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 {
FileInputStream fs = new FileInputStream(file);
DataInputStream ds = new DataInputStream(fs);
text = ds.readLine();
ds.close();
fs.close();
} catch (Exception ex) {
ex.printStackTrace();
fs = new FileInputStream(file);
ds = new DataInputStream(fs);
line = ds.readLine();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fs.close();
ds.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Long value = null;
if (text != null) {
if (line != null) {
try {
value = Long.parseLong(text);
value = Long.parseLong(line);
} catch (NumberFormatException nfe) {
value = null;
}
if (convertToMillis)
value = value / 1000; // convert to milliampere
value = value / 1000;
}
return value;
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册