Skip to content

Instantly share code, notes, and snippets.

@sungitly
Created March 30, 2016 02:52
Show Gist options
  • Save sungitly/b006a2656555202bf53087b290bb6521 to your computer and use it in GitHub Desktop.
Save sungitly/b006a2656555202bf53087b290bb6521 to your computer and use it in GitHub Desktop.
Collect Android Battery Usage
private void logBatteryInfoByApi() {
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = MainActivity.this.registerReceiver(null, ifilter);
assert batteryStatus != null;
Log.e(LOG_TAG, "STATUS: " + String.valueOf(batteryStatus.getIntExtra(BatteryManager
.EXTRA_STATUS, -1)));
Log.e(LOG_TAG, "PLUG: " + String.valueOf(batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED,
-1)));
Log.e(LOG_TAG, "LEVEL: " + String.valueOf(batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL,
-1)));
Log.e(LOG_TAG, "SCALE: " + String.valueOf(batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE,
-1)));
Log.e(LOG_TAG, "TEMP: " + String.valueOf(batteryStatus.getIntExtra(BatteryManager
.EXTRA_TEMPERATURE, -1)));
Log.e(LOG_TAG, "HEALTH: " + String.valueOf(batteryStatus.getIntExtra(BatteryManager.EXTRA_HEALTH,
-1)));
Log.e(LOG_TAG, "VOLTAGE: " + String.valueOf(batteryStatus.getIntExtra(BatteryManager
.EXTRA_VOLTAGE,
-1)));
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
BatteryManager batteryManager = (BatteryManager) getSystemService(Context.BATTERY_SERVICE);
Log.e(LOG_TAG, "CAP: " + String.valueOf(batteryManager.getIntProperty(BatteryManager
.BATTERY_PROPERTY_CAPACITY)));
Log.e(LOG_TAG, "COUNTER: " + String.valueOf(batteryManager.getIntProperty(BatteryManager
.BATTERY_PROPERTY_CHARGE_COUNTER)));
Log.e(LOG_TAG, "CURRENT_AVG: " + String.valueOf(batteryManager.getIntProperty(BatteryManager
.BATTERY_PROPERTY_CURRENT_AVERAGE)));
Log.e(LOG_TAG, "CURRENT: " + String.valueOf(batteryManager.getIntProperty(BatteryManager
.BATTERY_PROPERTY_CURRENT_NOW)));
Log.e(LOG_TAG, "ENERGY: " + String.valueOf(batteryManager.getIntProperty(BatteryManager
.BATTERY_PROPERTY_ENERGY_COUNTER)));
}
}
private void logBatteryInfoBySysFile() {
Properties props = new Properties();
File file = new File("/sys/class/power_supply/Battery/uevent");
try {
InputStream in = new FileInputStream(file);
props.load(in);
Log.e(LOG_TAG, props.getProperty("POWER_SUPPLY_STATUS"));
} catch (IOException e) {
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment