Android Kotlin: How to get device battery level programmatically

This code snippet demonstrates how to retrieve the current battery level of an Android device programmatically using Kotlin. It achieves this by leveraging the Android system's built-in broadcast mechanism.

Explanation:

  1. Broadcast Receiver:

    • The code defines a BroadcastReceiver subclass. This receiver is designed to listen for specific system broadcasts.
    • In this case, the receiver listens for the Intent.ACTION_BATTERY_CHANGED broadcast, which gets sent by the system whenever the battery level or charging state changes.
  2. Registering Receiver:

    • Inside the onCreate method of the MainActivity, an IntentFilter instance is created. This filter specifies the type of broadcasts the receiver wants to listen for (in this case, Intent.ACTION_BATTERY_CHANGED).
    • The registerReceiver method is then called to register the created receiver with the system, along with the defined filter.
  3. Handling Battery Level Update:

    • When the onReceive method of the receiver is called upon receiving the ACTION_BATTERY_CHANGED broadcast, it retrieves information about the battery level from the intent object.
    • The getIntExtra method is used twice to extract two key values:
      • EXTRA_SCALE: This integer represents the device's maximum battery level.
      • EXTRA_LEVEL: This integer represents the current battery level, with a range of 0 (empty) to EXTRA_ SCALE (full).
    • Finally, the retrieved level and scale information are displayed on the TextView element within the activity's layout using string formatting.

Summary

By registering a broadcast receiver for battery changes and processing the received information, this code effectively retrieves and displays the current battery level on the device. This approach offers a convenient way to integrate battery level information within your Android application. It's important to note that constantly monitoring the battery level can drain the battery itself. Consider implementing strategies for efficient updates based on your application's needs.


MainActivity.kt

package com.example.jetpack

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    // initialize a new broadcast receiver instance
    private val receiver:BroadcastReceiver = object: BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            // get battery current level and scale from intent
            intent?.apply {
                // integer containing the maximum battery level
                val scale = getIntExtra(
                    BatteryManager.EXTRA_SCALE, -1
                )

                //  integer field containing the current battery
                //  level, from 0 to EXTRA_SCALE
                val level = getIntExtra(
                    BatteryManager.EXTRA_LEVEL, -1
                )

                textView.text = "Battery current level $level\n(Range 0 to $scale)"
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // initialize a new intent filter instance
        val filter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)

        // register the broadcast receiver
        registerReceiver(receiver,filter)
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EDEAE0"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:padding="32dp"
        android:textColor="#0014A8"
        android:textSize="35sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.25"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials