Home > Java > javaTutorial > How Can I Get the Battery Level and Status in Android?

How Can I Get the Battery Level and Status in Android?

Linda Hamilton
Release: 2024-10-30 16:50:26
Original
953 people have browsed it

How Can I Get the Battery Level and Status in Android?

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

Getting Battery State

To determine the battery's current state, check the value of bm.getIntProperty(BatteryManager.BATTERY_STATUS):

  • BATTERY_STATUS_UNKNOWN: Unknown battery state.
  • BATTERY_STATUS_CHARGING: Battery is charging.
  • BATTERY_STATUS_DISCHARGING: Battery is discharging.
  • BATTERY_STATUS_NOT_CHARGING: Battery is not charging.
  • BATTERY_STATUS_FULL: Battery is fully charged.

Additional Constants

BatteryManager also provides constants for other battery-related information:

  • BATTERY_HEALTH_UNKNOWN: Unknown battery health.
  • BATTERY_HEALTH_GOOD: Battery is healthy.
  • BATTERY_HEALTH_OVERHEAT: Battery is overheating.
  • BATTERY_HEALTH_DEAD: Battery is dead.
  • BATTERY_TECH_UNKNOWN: Unknown battery technology.
  • BATTERY_TECH_LION: Battery uses lithium-ion technology.

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template