Question: I'm trying to run some code every time the charger gets connected to the device and the app is closed. The only thing I've found is to schedule a job that only can run when the charger is connected, but the problem with that is that the code will only run once (unless I reschedule it ofc) and it will only run at the set times. I want the code to run immediately and every time I connect the charger, like a broadcastlistener, but in the background.

Is this possible or do you have some other suggestions?

Thanks in advance! :)

EDIT:
It seems like you can't listen to these kinds of broadcasts anymore if you're running API level 26+ [ref](https://developer.android.com/guide/components/broadcast-exceptions.html)

Answer: 
You could use a `JobScheduler`, and use the [`setRequiresCharging(boolean requiresCharging)`](https://developer.android.com/reference/android/app/job/JobInfo.Builder.html#setRequiresCharging(boolean)) method on the `JobInfo.Builder` you create.
The BatteryManager broadcasts an action whenever the device is connected or disconnected from power. It's important to receive these events even while your app isn't running—particularly as these events should impact how often you start your app in order to initiate a background update—so you should register a BroadcastReceiver in your manifest to listen for both events by defining the ACTION\_POWER\_CONNECTED and ACTION\_POWER\_DISCONNECTED within an intent filter.

```
<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>

```

Within the associated BroadcastReceiver implementation, you can extract the current charging state and method as described in the previous step.

```
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 == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
    }
}

```

Ref: <https://developer.android.com/training/monitoring-device-state/battery-monitoring>