Search code examples
javaandroidbroadcastreceiverpower-management

Does a BroadcastReceiver only listen to changes?


I was reading the guide here about setting up a BroadcastReceiver to check changes in the battery. And it stated that I could setup a BroadcastReceiver like this:

<receiver android:name=".PowerConnectionReceiver">
    <intent-filter>
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
        <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
    </intent-filter>
</receiver>

in my manifest and this as a class:

public class PowerConnectionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) { 
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                        status == BatteryManager.BATTERY_STATUS_FULL;

        int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;
    }
}

Is the BroadcastReceiver call onReceive(...) ONLY when a CHANGE occurs in the battery state? For example, what if the user had the device plugged into their computer and it was charging the entire time the BroadcastReceiver was running. Would it detect a change, since technically, the device's battery status didn't change? Whenever I get isCharging, would it be the current value, or the value at the last change? I want to check if it did change and what it always is so that I can optimize my application and save battery life.


Solution

  • It will get called only on these actions, as you specified...

    1. android.intent.action.ACTION_POWER_CONNECTED
    2. android.intent.action.ACTION_POWER_DISCONNECTED

    And that's when...

    1) External power has been connected to the device.

    2) External power has been removed from the device.

    If you need to track battery power changes, you should include this filter in your manifest.

    android.intent.action.ACTION_BATTERY_CHANGED

    Btw. isCharging would be the current state, of course.