This code snippet demonstrates how to retrieve the device's battery health status programmatically in an Android application written in Kotlin. It utilizes the Android Broadcast mechanism to listen for changes in the battery state and update the UI accordingly.
Code Breakdown:
Broadcast Receiver:
- A
BroadcastReceiver
subclass is defined within theMainActivity
class. This receiver listens for specific system events (broadcasts) related to the battery.
- A
onReceive
Method:- This method is invoked whenever the registered broadcast is received. It retrieves the battery health information from the
Intent
object using theBatteryManager.EXTRA_HEALTH
extra key.
- This method is invoked whenever the registered broadcast is received. It retrieves the battery health information from the
Battery Health Determination:
- A
when
expression is used to interpret the integer value obtained from theEXTRA_HEALTH
key. Each possible value corresponds to a specific battery health state like "Good", "Dead", or "Overheat". A default case handles unknown or error conditions.
- A
UI Update:
- The retrieved battery health status is displayed on the screen using the
textView
element referenced by its ID. The text is formatted as "Battery Health : <health_status>".
- The retrieved battery health status is displayed on the screen using the
onCreate
Method:- The
onCreate
method sets up the broadcast receiver functionality. - An
IntentFilter
object is created to specify the type of broadcast we're interested in (battery change event). - Finally, the
registerReceiver
method registers the created receiver with the system, along with the defined filter.
- The
activity_main.xml
:- This file defines the layout of the activity. In this case, it's a simple layout with a single
TextView
element to display the battery health information.
- This file defines the layout of the activity. In this case, it's a simple layout with a single
Summary
This code provides a basic example of fetching the device's battery health programmatically in an Android application. By registering a broadcast receiver and interpreting the received information, the app can display the current battery health status to the user. It's important to note that this approach only provides a limited set of health states and may not offer detailed diagnostics available on specific devices.
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 health = when(intent?.getIntExtra(
BatteryManager.EXTRA_HEALTH,-1
)){
// determine the battery health from intent
BatteryManager.BATTERY_HEALTH_COLD -> "Cold"
BatteryManager.BATTERY_HEALTH_DEAD -> "Dead"
BatteryManager.BATTERY_HEALTH_GOOD -> "Good"
BatteryManager.BATTERY_HEALTH_OVERHEAT -> "Over heat"
BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE -> "Over voltage"
BatteryManager.BATTERY_HEALTH_UNKNOWN -> "Unknown"
BatteryManager
.BATTERY_HEALTH_UNSPECIFIED_FAILURE -> "Unspecified failure"
else -> "Error"
}
textView.text = "Battery Health : $health"
}
}
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>
- android kotlin - Show soft keyboard when EditText is focused
- android kotlin - EditText allow only numbers
- android kotlin - EditText allow only characters
- android kotlin - EditText limit number range
- android kotlin - EditText input filter decimal
- android kotlin - EditText remove underline while typing
- android kotlin - EditText change cursor color programmatically
- android kotlin - EditText hide keyboard after enter
- android kotlin - EditText hide keyboard click outside
- android kotlin - Switch button listener
- android kotlin - Material switch button
- android kotlin - Get battery temperature programmatically
- android kotlin - Get battery status programmatically
- android kotlin - On back button pressed example
- android kotlin - Get string resource by name