I am trying to make an app that shows some information when you connect your phone to a charger during a specific period of the day.
Before Android Oreo this was easy, just add an Broadcast receiver and add android.intent.action.ACTION_POWER_CONNECTED to the intentfilter in the manifest.
Now I am struggling to find a working solution to create the same functionality. I thought about periodically checking the device charging state but this feels wrong and it won't trigger immediately on connecting the device to a charger.
Registering the broadcast receiver from my application did not work either, when the application is closed the broadcast isn't received anymore.
Is there a battery friendly way to trigger an action when an Android device is connected to a charger in Android Oreo?
There are broadcasts which are exempted from the background execution limitations and for which broadcast receivers can still be registered in the manifest.
You could use the ACTION_BOOT_COMPLETED broadcast to start a service which registers a receiver for your ACTION_POWER_CONNECTED broadcast at runtime. (The service must be a foreground service. Otherwise, it may be destroyed.)
A other solution would be to use JobScheduler to create a job which requires charging. Then you don't need the foreground service.