maephisto
maephisto

Reputation: 5182

Android battery/usage stats

How can one access the battery and usage information, in general and on a per-app basis ? On my S5 & S2 the information is displayed in the Settings/Battery menus but I can't find any reference on this in the Android SDK docs.

enter image description here

enter image description here

Upvotes: 1

Views: 471

Answers (1)

Gilad Haimov
Gilad Haimov

Reputation: 5857

There is no 'formal' way of accessing per app battery usage. I know some hacks, but they are messy and will probably not work on >= Android 4.4.

You can, however, use debug time tools that provide per-app data. ATT ARO is by far the best of them.

When it comes to global battery usage things gets better.

From any point within your code you can get the current battery level by:

int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (level == -1 || scale == -1) {
   return 40f; // or any other default
}
float batteryLevelPercent = level / (float)scale;

If you are interested in ongoing monitoring of battery state, you could register a 'battery changed' receiver:

void registerBatteryStateListener() {
    BroadcastReceiver batteryStateListener = new BroadcastReceiver() {
        int scale = -1;
        int level = -1;
        int voltage = -1;
        int temp = -1;
        @Override
        public void onReceive(Context context, Intent intent) {
            level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
            voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
            Log.e("BatteryStat", "level = " + level + ", scale = " + scale);
        }
    };
    IntentFilter changeFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(batteryStateListener, changeFilter);
}

And add relevant permission to manifest:

 <uses-permission android:name="android.permission.BATTERY_STATS"></uses-permission>

Note that ACTION_BATTERY_CHANGED is a sticky intent. meaning it will basically run forever.

Upvotes: 1

Related Questions