Android Kotlin: How to get battery charging state programmatically

Introduction

This code snippet demonstrates how to programmatically determine the charging state of a device in an Android application written in Kotlin. It achieves this by utilizing the Android operating system's built-in broadcast mechanism.

Code Breakdown

The code is divided into two main parts: the MainActivity.kt file which handles the logic and the activity_main.xml file which defines the user interface.

MainActivity.kt:

  1. Broadcast Receiver:

    • A BroadcastReceiver subclass is defined. This class will be notified whenever the battery state changes.
    • The onReceive method is overridden to handle the received broadcast.
  2. Obtaining Battery Status:

    • Inside onReceive, the intent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) retrieves the battery status code from the received intent.
    • A when statement is used to interpret the status code. Different codes correspond to different charging states (charging, discharging, full, etc.) and an error message is displayed for unknown codes.
  3. Updating UI:

    • The interpreted status string is then used to update the text displayed in the TextView with the ID textView.
  4. Setting Up Broadcast Receiver:

    • In onCreate, an IntentFilter instance is created with the action Intent.ACTION_BATTERY_CHANGED. This action signifies a change in battery state.
    • The registerReceiver method registers the previously defined broadcast receiver with the created intent filter. This essentially tells the system to notify this receiver whenever the battery state changes.

Activity_main.xml

This file defines the layout of the application's main activity. It consists of a single TextView element with the ID textView which will display the current battery charging status.

Summary

By registering a broadcast receiver for battery state changes and interpreting the received information, this code effectively retrieves the device's charging status and displays it on the screen. This approach allows developers to implement functionalities that may require knowledge of the device's charging state.


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?) {
            val status = when(intent?.getIntExtra(
                BatteryManager.EXTRA_STATUS,-1
            )){
                BatteryManager.BATTERY_STATUS_UNKNOWN -> "Unknown"
                BatteryManager.BATTERY_STATUS_CHARGING -> "Charging"
                BatteryManager.BATTERY_STATUS_DISCHARGING -> "Discharging"
                BatteryManager.BATTERY_STATUS_NOT_CHARGING -> "Not charging"
                BatteryManager.BATTERY_STATUS_FULL -> "Full"
                else -> "Error"
            }

            textView.text = "Battery status : $status"
        }
    }

    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"
        tools:text="TextView" />

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