我有一个简单的 Android Kotlin 应用程序,它的部分功能是在连接和断开电源并执行操作时进行监听
这是我的旧代码,它在针对 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>
Run Code Online (Sandbox Code Playgroud)
充电实用程序
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`
}
}
}
Run Code Online (Sandbox Code Playgroud)
在以后的 Android 版本中,如何实现广播有一些变化:https : //developer.android.com/guide/components/broadcasts
到目前为止我尝试过的:
所以我的问题是:
连接/断开电源时如何调用函数?同时考虑到运行 Android 8 …