Accessing Battery Information in Android
Question: How to obtain the battery's level and state (e.g., plugged in, discharging, charging) in Android?
Answer:
Android provides the BatteryManager class to manage battery-related information. Contrary to its name, it does not contain any methods but defines constants that represent different battery states and properties.
Usage:
Since Android SDK 21 (Lollipop), you can use the following code to retrieve the current battery level as a percentage:
<code class="java">BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE); int batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);</code>
This code snippet fetches the battery level from the BatteryManager, which is accessible via the BATTERY_SERVICE system service. Note that context represents the current application context.
Additional Information:
Other useful constants defined in BatteryManager include:
The above is the detailed content of How to Retrieve Battery Level and State Information in Android?. For more information, please follow other related articles on the PHP Chinese website!