get battery voltage in android programmatically

Sometimes when you are developing an android application, you may want to get current batter voltage

In this post, we are going to see how to get current battery voltage in android. You can use intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE,0) to get information about current battery voltage.

Source code:

Download
click to begin

20KB .zip

Step 1 :

Create an android application project named “GetBatteryVoltageApp”.

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 :

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *