Skip to content

Battery Status

Question

You need to get info about battery status in the device? What mechanism can you use?

Short interview answer

Use a BroadcastReceiver when the app must react to power-state changes. Register for ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED; the receiver can adjust or reschedule work when charging begins or ends.

Detailed answer

For example, a Xamarin.Android receiver can change an app’s background-update policy when the device is plugged in or unplugged:

[BroadcastReceiver(Enabled = true, Exported = false)]
[IntentFilter(new[] { Intent.ActionPowerConnected, Intent.ActionPowerDisconnected })]
public sealed class PowerConnectionReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        var isCharging = intent.Action == Intent.ActionPowerConnected;
        var state = isCharging ? "charging" : "not charging";
        Android.Util.Log.Info("PowerConnection", state);
    }
}

The Log call only makes the received state observable in this example; it is not a proposed application feature. The point is that OnReceive gets a real power-change event. For actual deferrable work such as a large upload, do not build a receiver that manually tracks charging state: declare WorkManager’s RequiresCharging constraint and let Android run the worker only while charging. For a one-off current level, query the sticky ACTION_BATTERY_CHANGED intent and read its level and scale extras instead.

Sources