This code snippet demonstrates how to retrieve the current battery percentage programmatically in an Android application written in Kotlin. It utilizes the Android Broadcast system to listen for changes in battery level and update a TextView accordingly.
Explanation:
- Broadcast Receiver:
- The code defines a custom
BroadcastReceiver
subclass. This receiver will be notified whenever the battery level changes on the device.
- The code defines a custom
- Intent Filter:
- An
IntentFilter
object is created to specify the type of broadcasts the receiver is interested in. In this case, it filters for broadcasts with the actionIntent.ACTION_BATTERY_CHANGED
.
- An
- Registering Receiver:
- Inside the
onCreate
method of theMainActivity
, theregisterReceiver
method is called to register the custom broadcast receiver with the system. TheIntentFilter
object is passed as an argument to specify the type of broadcasts it should listen for.
- Inside the
- Updating Text View:
- When the battery level changes, the
onReceive
method of the broadcast receiver is called. - Inside this method, the
currentBatteryCharge
extension property of the receivedIntent
is used to retrieve the battery percentage. - Finally, the retrieved percentage is displayed on a TextView with the ID
textView
in the layout.
- When the battery level changes, the
- Extension Property:
- The code defines an extension property for the
Intent
class namedcurrentBatteryCharge
. - This property retrieves the raw battery level (
EXTRA_LEVEL
) and scale (EXTRA_SCALE
) values from theBatteryManager
extras within the intent. - It then calculates the percentage by dividing the level by the scale and multiplying by 100.
- The code defines an extension property for the
Summary
By combining the broadcast receiver and the extension property, this code efficiently obtains the current battery percentage and displays it on the screen whenever the battery level changes. It provides a clear and concise approach to programmatically access battery information in an Android application using Kotlin.
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?) {
intent?.apply {
textView.text = "Current battery charge\n$currentBatteryCharge%"
}
}
}
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 get current battery charge percentage from intent
val Intent.currentBatteryCharge:Float
get() {
// 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
)
// return current battery charge percentage
return level * 100 / scale.toFloat()
}
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 - ImageView set image from Uri
- android kotlin - Get battery capacity programmatically
- android kotlin - Get battery level programmatically
- android kotlin - Get battery voltage programmatically
- android kotlin - Get battery status programmatically
- android kotlin - On back button pressed example
- android kotlin - Get string resource by name
- android kotlin - Paint gradient path
- android kotlin - Paint linear gradient
- android kotlin - Paint gradient circle
- android kotlin - Canvas draw text
- android kotlin - Canvas draw circle