Home > Java > javaTutorial > body text

How to Retrieve Battery Level and State Information in Android?

DDD
Release: 2024-11-03 06:11:02
Original
555 people have browsed it

How to Retrieve Battery Level and State Information in Android?

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>
Copy after login

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:

    • BatteryManager.BATTERY_PLUGGED_AC (AC charger)
    • BatteryManager.BATTERY_PLUGGED_USB (USB charger)
    • BatteryManager.BATTERY_HEALTH_GOOD
    • BatteryManager.BATTERY_STATE_CHARGING
  • Consult the Android Developers documentation for more details on BatteryManager and battery management in Android: [Read BatteryManager | Android Developers - BATTERY_PROPERTY_CAPACITY](https://developer.android.com/reference/android/os/BatteryManager#BATTERY_PROPERTY_CAPACITY)

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template