Retrieving Battery Level and State in Android
To monitor the status of your device's battery, the Android SDK provides the BatteryManager class. Despite its unintuitive name, BatteryManager doesn't contain any methods. Instead, it's a collection of constants that describe the various battery-related states your device can be in.
Getting Battery Level
Starting with SDK 21 (Lollipop), you can retrieve the current battery level as a percentage using the following code snippet:
<code class="java">BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE); int batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);</code>
Getting Battery State
To determine the battery's current state, check the value of bm.getIntProperty(BatteryManager.BATTERY_STATUS):
Additional Constants
BatteryManager also provides constants for other battery-related information:
The above is the detailed content of How Can I Get the Battery Level and Status in Android?. For more information, please follow other related articles on the PHP Chinese website!