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.
Keep running a thread in the background and use this method

```
public static boolean isConnected(Context context) {
    Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
}

```

if `isConnected()` returns `true` then update the time.

[Code reference](https://stackoverflow.com/a/45459483/10305444)