I have a simple Android Kotlin app, and part of what it does is listen for when power is connected and disconnected and perform an action
This is my old code, and it worked totally fine while targeting devices below Oreo.
AndroidManifest.xml
<receiver android:name=".ChargingUtil$PlugInReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
ChargingUtil.kt
class ChargingUtil (context: Context){
/*... Some other charging-related functions here ... */
class PlugInReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d("thisistest", "Power was changed")
// Here I do some logic with `intent.action`
}
}
}
There have been some changes to how to implement Broadcasts, in later Android versions: https://developer.android.com/guide/components/broadcasts
What I've tried so far:
- I tried following this documentation, but their implementation is actually the same as my current code (which only works below Android 8).
- I also found this question, but the only solution, was to periodically check if power is connected or not. I don't think that is so viable for me, since my app needs to know instantly when the charging state is changed.
So my question is:
How to call a function when power is connected/ disconnected? While taking account of the additional restrictions that systems running Android 8 or later impose on manifest-declared receivers.
Note: I am using Kotlin, and would like to avoid the use of deprecated packages
I am a bit of a noob when it comes to Android, so sorry if there is actually an obvious solution what I just missed. Thanks in advance for any help.