Learn to Monitor Battery Status in Android

In this tutorial, you will learn how to develop an Android application using Kotlin that monitors and displays the battery status of the device. The tutorial will guide you through the process of implementing functionality to retrieve information such as whether the device is charging or discharging, and the current battery level. This involves utilizing Android's BatteryManager and BroadcastReceiver to listen for changes in battery status, ensuring your app updates dynamically based on these events. By following this step-by-step guide, you'll gain practical experience in accessing system-level information, handling broadcast events, and displaying real-time battery status information within your Kotlin-based Android applications.
Submitted on July 07, 2024

To create an Android app that displays the battery status (charging, discharging, battery level), you'll need to use Android's BatteryManager and BroadcastReceiver to listen for battery status changes. Below is a step-by-step guide to implement this in Kotlin:

Step-by-Step Implementation

1. Modify activity_main.xml:

  • Open ‘res/layout/activity_main.xml’ and add TextViews to display battery status information.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <TextView
            android:id="@+id/textViewStatus"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Battery Status: "
            android:textSize="18sp"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="32dp" />

        <TextView
            android:id="@+id/textViewLevel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Battery Level: "
            android:textSize="18sp"
            android:layout_below="@id/textViewStatus"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="16dp" />

    </RelativeLayout>

    

Implement MainActivity.kt

  • Open ‘MainActivity.kt’ and implement logic to monitor battery status using BroadcastReceiver.

    package com.example.batterystatus

    import android.content.BroadcastReceiver
    import android.content.Context
    import android.content.Intent
    import android.content.IntentFilter
    import android.os.BatteryManager
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.widget.TextView

    class MainActivity : AppCompatActivity() {

        private lateinit var textViewStatus: TextView
        private lateinit var textViewLevel: TextView

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

            textViewStatus = findViewById(R.id.textViewStatus)
            textViewLevel = findViewById(R.id.textViewLevel)

            // Register broadcast receiver to monitor battery status
            registerBatteryLevelReceiver()
        }

        private fun registerBatteryLevelReceiver() {
            val batteryLevelReceiver = object : BroadcastReceiver() {
                @Override
                override fun onReceive(context: Context?, intent: Intent?) {
                    val action = intent?.action
                    if (action == Intent.ACTION_BATTERY_CHANGED) {
                        val status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
                        val isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                                status == BatteryManager.BATTERY_STATUS_FULL

                        val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                        val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
                        val batteryPct = level * 100 / scale.toFloat()

                        if (isCharging) {
                            textViewStatus.text = "Battery Status: Charging"
                        } else {
                            textViewStatus.text = "Battery Status: Discharging"
                        }
                        textViewLevel.text = "Battery Level: ${batteryPct.toInt()}%"
                    }
                }
            }

            val filter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
            registerReceiver(batteryLevelReceiver, filter)
        }

        @Override
        override fun onDestroy() {
            super.onDestroy()
            // Unregister the receiver when the activity is destroyed
            unregisterReceiver(batteryLevelReceiver)
        }
    }

    

Explanation:

  • ‘activity_main.xml’: Contains TextViews (‘textViewStatus’ and ‘textViewLevel’) to display battery status (charging or discharging) and battery level percentage.
  • ‘MainActivity.kt’:
    • ‘onCreate()’: Initializes TextViews and registers a BroadcastReceiver (‘batteryLevelReceiver’) to monitor battery status changes.
    • ‘registerBatteryLevelReceiver()’: Creates a BroadcastReceiver that listens for ‘ACTION_BATTERY_CHANGED’ broadcasts, retrieves battery status (‘EXTRA_STATUS’) and battery level (‘EXTRA_LEVEL’), calculates battery percentage, and updates the TextViews accordingly.
    • ‘onDestroy()’: Unregisters the BroadcastReceiver to release resources when the activity is destroyed.

Testing:

  • Run the app on an emulator or a physical device.
  • Observe the TextViews (textViewStatus’ and textViewLevel’) to see the battery status (charging or discharging) and battery level percentage update in real-time as you plug/unplug the device.

This implementation provides a simple way to monitor and display battery status (charging or discharging) and battery level percentage in an Android app using Kotlin.