get battery level and state in android programmatically

Previous
Next
Sometimes when you are developing an android application, you may want to get current batter level or state.
For example:
Lets say you want to make a rule that if battery level is less than 15%, turn off all background processes in android.
In this post, we are going to see how to get current battery level and state in android.
There are five android battery state which you must know.

  • BatteryManager.BATTERY_STATUS_CHARGING
  • BatteryManager.BATTERY_STATUS_DISCHARGING
  • BatteryManager.BATTERY_STATUS_FULL
  • BatteryManager.BATTERY_STATUS_UNKNOWN
  • BatteryManager.BATTERY_STATUS_NOT_CHARGING

Source code:

Download

click to begin
20KB .zip

 Step 1 :

Create an android application project named “GetBatteryInfoApp”.

Step 2 :

Change res ->layout -> activity_main.xml as below:

Step 3:

Change src/main/packageName/MainActivity.java as below:

As we want to get battery level change information, we need to register broadcast receiver and intent filter. An intent filter is used to tell native battery app that this app is listening for changes in native battery app.
Lets understand above code:

Intent.ACTION_BATTERY_CHANGED:

If you see the code we have used Intent.ACTION_BATTERY_CHANGED to get current battery info. It is sticky broadcast which contain battery charging state , level and other info. BatteryManager class contains all constant strings.
Sticky broadcast is broadcast which will remain active once registered.

Here we are registering created broadcastreceiver to the MainActivity and intent filter is listening for battery change events.

Run the app:

When you run above app on actual device, you will get below screen :

When you click on button, you will get below screen :

So it shows current battery state and level.

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog