How Can My App React to Power Connecting/Disconnecting Even When Closed?

15 hours ago 3
ARTICLE AD BOX

I have tried creating a context-registered receiver following the docs and other examples on StackOverflow, but for some reason none of these logs ever fire. Not when the app is open, not when it's closed - never.

Using ACTION_POWER_CONNECTED and BroadcastReceiver did not work for me.

Forgive me if I'm making a basic mistake as it's been quite awhile since I've done Android development.

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.ChargeAlert"> <activity android:name=".MainActivity" android:exported="true" android:theme="@style/Theme.ChargeAlert"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".Alerts" android:exported="true"> <intent-filter> <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/> <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/> </intent-filter> </receiver> </application> </manifest>

Alerts.kt:

import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log class Alerts : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { Log.d("ChargeAlert", "BroadcastReceiver().onReceive called!") when (intent?.action) { Intent.ACTION_POWER_CONNECTED -> { Log.d("ChargeAlert", "Power connected") } Intent.ACTION_POWER_DISCONNECTED -> { Log.d("ChargeAlert", "Power disconnected") } } } }

Registering directly into MainActivity.kt does work, but only fires when the app is open. I want these logs to fire even when my app is closed.

val alerts = Alerts() val intentFilter = IntentFilter() intentFilter.addAction(Intent.ACTION_POWER_CONNECTED) intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED) this.registerReceiver(alerts, intentFilter)
Read Entire Article