get battery level and state in android programmatically

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:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.java2blog.getbatteryinfoapp.MainActivity">

    <TextView
        android:id="@+id/textViewBatteryStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Current Battery Status"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/buttonBatteryStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textViewBatteryStatus"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:text="Click here to Get battery Info" />
</RelativeLayout>

Step 3:

Change src/main/packageName/MainActivity.java as below:
package com.java2blog.checkbatterystatusapp;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.java2blog.checkbatterystatusapp.R;

public class MainActivity extends Activity {

    TextView textview;
    Button button;
    IntentFilter intentfilter;
    int deviceStatus;
    String currentBatteryStatus="Battery Info";
    int batteryLevel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button)findViewById(R.id.buttonBatteryStatus);
        textview = (TextView)findViewById(R.id.textViewBatteryStatus);

        intentfilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                MainActivity.this.registerReceiver(broadcastreceiver,intentfilter);

            }
        });

    }

    private BroadcastReceiver broadcastreceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            deviceStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS,-1);
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            int batteryLevel=(int)(((float)level / (float)scale) * 100.0f);

            if(deviceStatus == BatteryManager.BATTERY_STATUS_CHARGING){

                textview.setText(currentBatteryStatus+" = Charging at "+batteryLevel+" %");

            }

            if(deviceStatus == BatteryManager.BATTERY_STATUS_DISCHARGING){

                textview.setText(currentBatteryStatus+" = Discharging at "+batteryLevel+" %");

            }

            if (deviceStatus == BatteryManager.BATTERY_STATUS_FULL){

                textview.setText(currentBatteryStatus+"= Battery Full at "+batteryLevel+" %");

            }

            if(deviceStatus == BatteryManager.BATTERY_STATUS_UNKNOWN){

                textview.setText(currentBatteryStatus+" = Unknown at "+batteryLevel+" %");
            }


            if (deviceStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING){

                textview.setText(currentBatteryStatus+" = Not Charging at "+batteryLevel+" %");

            }

        }
    };
}
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.
MainActivity.this.registerReceiver(broadcastreceiver,intentfilter);
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.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012