Android Kotlin: Programmatically Get Battery Voltage
This code demonstrates how to retrieve the battery voltage level in volts on an Android device using Kotlin. It utilizes the Android Broadcast system to listen for battery level changes and extract the voltage information.
Code Breakdown:
Broadcast Receiver:
- A
BroadcastReceiver
subclass is defined to capture battery level updates. - The
onReceive
method gets called whenever the battery level changes.
- A
Extracting Voltage:
- Inside
onReceive
, the intent's extra value forBatteryManager.EXTRA_VOLTAGE
is retrieved in millivolts (mV).
- Inside
Converting to Volts:
- An extension property
toVolts
is defined forInt
. - It converts the millivolt value to volts by dividing by 1000.
- A
DecimalFormat
object is used to format the voltage with one decimal place and round it up usingRoundingMode.CEILING
.
- An extension property
Activity & UI:
- The
MainActivity
class extendsAppCompatActivity
and handles the UI. - An
IntentFilter
is created to listen for theIntent.ACTION_BATTERY_CHANGED
broadcast. - The
receiver
instance is registered inonCreate
to start listening for battery updates. - The
textView
in the layout displays the formatted battery voltage.
- The
Summary
This code provides a way to programmatically access and display the battery voltage level on an Android device. It leverages the Android Broadcast system to stay updated on battery level changes and performs unit conversion and formatting for a user-friendly presentation.
This approach is beneficial for applications that require detailed battery information beyond the standard percentage level. However, keep in mind that battery voltage access may not be available on all devices or Android versions.
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.*
import java.math.RoundingMode
import java.text.DecimalFormat
class MainActivity : AppCompatActivity() {
// initialize a new broadcast receiver instance
private val receiver:BroadcastReceiver = object: BroadcastReceiver(){
override fun onReceive(context: Context?, intent: Intent?) {
// get battery voltage in Millivolts from intent
val voltage = intent?.getIntExtra(
BatteryManager.EXTRA_VOLTAGE, 0
)
voltage?.apply {
// show the battery voltage in volts
textView.text = "Battery Voltage\n\n$toVolts"
}
}
}
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)
}
}
// extension property to convert milli volts to volts
val Int.toVolts:String
get() {
// convert Millivolts to Volts
val volts = this * 0.001
// initialize a new decimal format instance
val decimalFormat = DecimalFormat("#.#")
// round the number using decimal format
decimalFormat.roundingMode = RoundingMode.CEILING
// format the decimal value to one decimal position
return "${decimalFormat.format(volts)} Volts"
}
<?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 - ImageView set image from Uri
- android kotlin - Get battery capacity programmatically
- android kotlin - Get battery percentage programmatically
- android kotlin - Get battery level programmatically
- android kotlin - Get battery status programmatically
- android kotlin - On back button pressed example
- android kotlin - Get string resource by name
- android kotlin - Enable disable bluetooth programmatically
- android kotlin - Change screen orientation programmatically
- android kotlin - Change orientation without restarting activity
- android kotlin - Get screen size programmatically
- android kotlin - RecyclerView animation
- android kotlin - RecyclerView smooth scroll
- android kotlin - Border/divider between GridView items
- android kotlin - GridView OnItemClickListener