Home >Java >javaTutorial >How to Retrieve Battery Level and State in Android?

How to Retrieve Battery Level and State in Android?

DDD
DDDOriginal
2024-10-29 20:57:29562browse

How to Retrieve Battery Level and State in Android?

Obtain Battery Information in Android: Level and State

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:

  • BATTERY_HEALTH_UNKNOWN
  • BATTERY_HEALTH_GOOD
  • BATTERY_HEALTH_OVERHEAT
  • BATTERY_HEALTH_DEAD
  • BATTERY_STATUS_DISCHARGING
  • BATTERY_STATUS_NOT_CHARGING
  • BATTERY_STATUS_CHARGING
  • BATTERY_STATUS_FULL

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!

Statement:
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