Open In App
Related Articles

How to Check the Battery Level in Android Programmatically?

Like Article
Save Article
Report issue

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. 

Battery Level


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"?>
        android:text="show battery percentage"


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 android.os.Bundle
import android.widget.Toast
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // Declare button, that will show battery percentage when clicked
        val btn = findViewById<Button>(
        // 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()


Output: Run on Emulator

Last Updated : 23 Feb, 2021
Like Article
Save Article
Share your thoughts in the comments
Similar Reads