Accessing battery-related information is crucial for developing power-efficient and user-friendly Android applications. This guide explores how to retrieve the battery level and state using the BatteryManager class.
Understanding the BatteryManager Class
BatteryManager is a system service that provides access to battery information. While it doesn't have explicit methods, it offers a collection of constants that represent battery-related properties. These properties can be used to query the current battery status.
Retrieving Battery Level Percentage
From API level 21 (Lollipop) onwards, you can easily obtain the battery level as a percentage value:
<code class="java">BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE); int batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);</code>
The getIntProperty() method takes a property constant and returns the corresponding integer value. In this case, BATTERY_PROPERTY_CAPACITY provides the battery level in percentage.
Determining Battery State
The BatteryManager also provides several constants that represent different battery states:
To determine the current battery state, use the getIntentExtra() method with an appropriate BATTERY_STATUS_ or BATTERY_HEALTH_ constant:
<code class="java">Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);</code>
The above is the detailed content of How to Retrieve Battery Level and State in Android?. For more information, please follow other related articles on the PHP Chinese website!