Skip to content
DeveloperMemos

How to Get an Android Device's Battery Level Using BatteryManager

Kotlin, Android, Battery1 min read

If you want to get the battery level of an Android device using Kotlin and BatteryManager, you can follow these steps:

  1. Start by adding the BatteryManager class to your project. This class is part of the Android framework and provides access to battery-related information and operations. To add it to your project, you can either import it using the import keyword or use the fully qualified class name, which is android.os.BatteryManager.

  2. In your Kotlin code, you can get a reference to the BatteryManager instance by calling the getSystemService() method on your Context object, passing in the BATTERY_SERVICE constant as the argument. This method returns a BatteryManager instance, which you can then use to access battery-related information and operations.

1// Get a reference to the BatteryManager instance
2val batteryManager = context.getSystemService(BATTERY_SERVICE) as BatteryManager
  1. Once you have a reference to the BatteryManager instance, you can use its getIntProperty() method to get the battery level. This method takes two arguments: the property you want to get (in this case, the BATTERY_PROPERTY_CAPACITY constant) and a default value to use if the property is not available. This method returns an integer value representing the battery level, in percentage.
1// Get the battery level
2val batteryLevel = batteryManager.getIntProperty(BATTERY_PROPERTY_CAPACITY, 0)
  1. You can then use the battery level value in your code as needed. For example, you could display the battery level in a TextView, or use it to trigger certain actions when the battery level reaches a certain threshold.
1// Display the battery level in a TextView
2textView.text = "$batteryLevel%"
3
4// Trigger an action when the battery level reaches a certain threshold
5if (batteryLevel <= 20) {
6 // Battery level is low, do something
7}

In conclusion, getting the battery level of an Android device using Kotlin and BatteryManager is a simple process that involves getting a reference to the BatteryManager instance, using its getIntProperty() method to get the battery level, and then using the value in your code as needed. With these steps, you can easily integrate battery-related functionality into your Kotlin-based Android app.