Sometimes, it is useful to determine the current battery level. One may choose to reduce the rate of your background updates if the battery charge is below a certain level. But one cannot continuously monitor the battery state. In general, the impact of constantly monitoring the battery level has a more significant impact on the battery than the application’s normal behavior. So it’s always better to only monitor substantial changes in battery level. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
Approach
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file, which represents the UI of the project. Add a Button, so whenever the user will click on the Button a Toast message with battery percentage will be popped up on the screen. Below is the code for the activity_main.xml file.
<? xml version = "1.0" encoding = "utf-8" ?>
< RelativeLayout android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
< Button
android:id = "@+id/showBtn"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_centerInParent = "true"
android:text = "show battery percentage"
/>
</ RelativeLayout >
|
Step 3: Working with the MainActivity.kt file
Finally, go to the MainActivity.kt file, and refer the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
import android.os.BatteryManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Declare button, that will show battery percentage when clicked
val btn = findViewById<Button>(R.id.showBtn)
btn.setOnClickListener{
// Call battery manager service
val bm = applicationContext.getSystemService(BATTERY_SERVICE) as BatteryManager
// Get the battery percentage and store it in a INT variable
val batLevel:Int = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
// Display the variable using a Toast
Toast.makeText(applicationContext, "Battery is $batLevel%" ,Toast.LENGTH_LONG).show()
}
}
} |