title: How do I detect if device is charging from background
body: <p>I have searched thick and thin through the Developer notes for android and am unable to find out how to perform a specific action when a device is plugged in, and perform another action when unplugged.</p>
  <p>I have attempted to set a Broadcast Receiver like below however it will not run:</p>
  <pre><code>    &lt;receiver android:name=&quot;.PowerConnectionReceiver&quot;&gt;
          &lt;intent-filter&gt;
              &lt;action android:name=&quot;android.intent.action.ACTION_POWER_CONNECTED&quot; /&gt;
              &lt;action android:name=&quot;android.intent.action.ACTION_POWER_DISCONNECTED&quot; /&gt;
          &lt;/intent-filter&gt;
      &lt;/receiver&gt;
  </code></pre>
  <p>I understand that from API 26 and up, you can no longer receive some broadcasts registered in the manifest, and must register them dynamically.</p>
  <p>I need to have this run in the background but can't figure out how? This article updated in 2019 (after api 26) implies that I should be able to do it.</p>
  <blockquote>
  <p>The charging status can change as easily as a device can be plugged in, so it's important to monitor the charging state for changes and alter your refresh rate accordingly.</p>
  <p>The BatteryManager broadcasts an action whenever the device is connected or disconnected from power. It's important to receive these events <strong>even while your app isn't running particularly as these events should impact how often you start your app in order to initiate a background update so you should register a BroadcastReceiver in your manifest to listen for both events by defining the ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED within an intent filter.</strong></p>
  </blockquote>
  <p>My end goal is to call the broadcast receiver whenever device is plugged in or unplugged.</p>
  <p>How would I go about implementing this?</p>