title: How to persistently get Battery level and Charging status in Android (Kotlin)?
body: <p>I want to get the battery level and charging status(plugged or unplugged) persistently for my app, i.e every 3-4 seconds, or better, only when it changes.</p>
  <p>Currently I am doing this:</p>
  <pre><code>        val bm = getSystemService(BATTERY_SERVICE) as BatteryManager 
           val manager = ContextCompat.getSystemService(this,NotificationManager::class.java) as NotificationManager 
           val intent = this.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) 
           val plugged = intent?.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) ?: -1 
           val chargingText = when (plugged) { 
               BatteryManager.BATTERY_PLUGGED_AC -&gt; { 
                   &quot;Charging via AC supply&quot; 
               } 
               BatteryManager.BATTERY_PLUGGED_USB -&gt; { 
                   &quot;Charging via USB&quot; 
               } 
               BatteryManager.BATTERY_PLUGGED_WIRELESS -&gt; { 
                   &quot;Charging by Wireless technology&quot; 
               } 
               else -&gt; { 
                   &quot;Discharging&quot; 
               } 
           } 
           val batLevel:Int = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
  </code></pre>
  <p>I put the above code in a fixed rate timer for a 3.5 sec interval.</p>
  <p>I think this is pretty expensive on battery as it runs on a Foreground service continuously. But I need to get the exact level persistently.</p>
  <p>Is there a better way to do it?</p>