Aspyct.org

Android: detecting charge state

| Comments

Battery is expensive. Not to say that you can’t buy one, but you really should use resources wisely when you develop a mobile application. Yet sometimes you need to do some long run process or heavy calculation.

For that matter, Android allows us to detect whether the device is plugged in and charging. Let’s see how.

One thing we can do is ask whether the device is plugged-in. That can easily be done with a few lines of code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public void checkBatteryState(View sender) {
    IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = registerReceiver(null, filter);

    int chargeState = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    String strState;

    switch (chargeState) {
        case BatteryManager.BATTERY_STATUS_CHARGING:
        case BatteryManager.BATTERY_STATUS_FULL:
            strState = "charging";
            break;
        default:
            strState = "not charging";
    }

    TextView tv = (TextView) findViewById(R.id.textView);
    tv.setText(strState);
}

Note that charge efficiency may change according to the type of power source. You may want to investigate the BatteryManager.EXTRA_PLUGGED to get more information.

Astute readers will notice that we used a sticky broadcast to get the status. It means we can also create a BroadcastReceiver to monitor changes for the battery status. This is left as an exercise to you, dear reader :)

You can checkout the example on github.

Comments