For my android app I need to monitor battery consumption for all the phones that are running the app. In the app there needs to be a button to start the monitoring and to stop it, and after the monitoring has stopped the battery monitoring output should be saved as txt on the phone itself. I've taken a look at batterystats already, but according to the documentation the monitoring process is initiated by connecting the device to a PC, and after monitoring reconnecting the device and making a dump.
So is it possible to start and stop the monitoring without connecting to a computer and save the output locally on the phone?
You can use a broadcast receiver to receive information about your battery, when there is a change.
private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context ctx, Intent intent) {
mLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, Const.VALUE_UNSET);
mTemperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, Const.VALUE_UNSET);
mStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS, Const.VALUE_UNSET);
mPlugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, Const.VALUE_UNSET);
mScale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, Const.VALUE_UNSET);
mHealth = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, Const.VALUE_UNSET);
mVoltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, Const.VALUE_UNSET);
mTechnology = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY);
}
Don't forget to (un-)register the receiver in your Activity (or Service, if it should run in background).
Register (onCreate / onStart...):
registerReceiver(mBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
Unregister (onPause / onDestory):
unregisterReceiver(...)
Writing into a file shouldn't be too hard, just search here on SO and don't forget to set permissions (for working with files as well):
<uses-permission android:name="android.permission.BATTERY_STATS"/>