How to implement the calculation of battery usage in Android applications?

I can find out the total percentage of the battery using BatteryManager .

I am trying to implement the logic of how much battery consumption is consumed for each application that I open until I close the application.

Is it possible to do this using BatteryManger or do any other services need to be initiated?

+4
source share
2 answers

This is because the power management API calls in Android are private and not subject to the developer. These APIs are only available through Reflection.

The main packages that are used internally by Android to obtain statistics from power management are stored in com.android.internal.os.* (For example, com.android.internal.os.BatteryStatsImpl ).

StackOverflow user Chris Thompson shared a repository containing tools and an application to handle what you want. You can find it here .

You can inspire yourself to what he has done and build something on top of it.

In addition, you can get preliminary battery statistics and processor load used by each application using adb shell dumpsys batteryinfo .

A simple strace dumpsys batteryinfo when you are in the adb shell can give you a hint on how this data is dumpsys extracted.

+2
source

You can use the broadcast receiver to get information about the batteries, I don’t know how often you get this data, but I think that at least this could be the starting point.

 public class Main extends Activity { private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context arg0, Intent intent) { int level = intent.getIntExtra("level", 0); //Do stuff with level } }; @Override public void onCreate(Bundle data) { super.onCreate(data); setContentView(R.layout.main); this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); } } 
+1
source

All Articles