电池信息保存在 /sys/class/power_supply/battery/
public class MainActivity extends Activity {
private boolean mIsStart = true;
private Toast mToast;
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
showToast(getCurrent());
if (mIsStart) {
mHandler.sendEmptyMessageDelayed(0, 1900);
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler.sendEmptyMessage(0);
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeMessages(0);
mIsStart = false;
}
private String getCurrent() {
String result = "null";
try {
Class systemProperties = Class.forName("android.os.SystemProperties");
Method get = systemProperties.getDeclaredMethod("get", String.class);
String platName = (String) get.invoke(null, "ro.hardware");
if (platName.startsWith("mt") || platName.startsWith("MT")) {
String filePath = "/sys/class/power_supply/battery/device/FG_Battery_CurrentConsumption";
result = "当前电流为:" + Math.round(getMeanCurrentVal(filePath, 5, 0) / 10.0f) + "mA";
result += ", 电压为:" + readFile("/sys/class/power_supply/battery/batt_vol", 0) + "mV";
} else if (platName.startsWith("qcom")) {
String filePath ="/sys/class/power_supply/battery/current_now";
int current = Math.round(getMeanCurrentVal(filePath, 5, 0) / 10.0f);
int voltage = readFile("/sys/class/power_supply/battery/voltage_now", 0) / 1000;
if (current < 0) {
result = "充电电流为:" + (-current) + "mA, 电压为:" + voltage + "mV";
} else {
result = "放电电流为:" + current + "mA, 电压为:" + voltage + "mV";
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private float getMeanCurrentVal(String filePath, int totalCount, int intervalMs) {
float meanVal = 0.0f;
if (totalCount <= 0) {
return 0.0f;
}
for (int i = 0; i < totalCount; i++) {
try {
float f = Float.valueOf(readFile(filePath, 0));
meanVal += f / totalCount;
} catch (Exception e) {
e.printStackTrace();
}
if (intervalMs <= 0) {
continue;
}
try {
Thread.sleep(intervalMs);
} catch (Exception e) {
e.printStackTrace();
}
}
return meanVal;
}
private int readFile(String path, int defaultValue) {
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(
path));
int i = Integer.parseInt(bufferedReader.readLine(), 10);
bufferedReader.close();
return i;
} catch (Exception localException) {
}
return defaultValue;
}
private void showToast(String content) {
if (mToast == null) {
mToast = Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT);
} else {
mToast.setText(content);
mToast.setDuration(Toast.LENGTH_SHORT);
}
mToast.show();
}
}
---------------------
作者:张永飞
来源:CSDN
原文:https://blog.csdn.net/zhangyongfeiyong/article/details/53641809
版权声明:本文为博主原创文章,转载请附上博文链接!