In this post we will talk about how get battery status on Android device. For this task we will use BroadcastReceiver.

What is BroadcastReceiver?
A broadcast receiver is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android application.

The system itself broadcast event all time, as example when system gets booted or an SMS arrived, etc.

Application description
Application display of battery level and update this value when battery level changed.
battery_level_screen

Create a project

For this project we will use Android studio.
First step is create a project.
Create a project in Android Studio step1

Create a project in Android Studio step2

Create a project in Android Studio step3

Create a project in Android Studio step3

Add a new string constant to string.xml file:

<string name="battery_level">Battery level:</string>

Update layout for activity, which called “activity_main.xml”.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:text="@string/battery_level"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="12dp"
        android:layout_marginRight="12dp"
        android:max="100"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_toRightOf="@+id/textView"
        android:layout_toEndOf="@+id/textView" />

</LinearLayout>

Create an inner class with our BroadcastReceiver realization.
private class BatteryBroadcastReceiver extends BroadcastReceiver {

    private final static String BATTERY_LEVEL = "level";

    @Override
    public void onReceive(Context context, Intent intent) {
        int level = intent.getIntExtra(BATTERY_LEVEL, 0);

        mBatteryLevelText.setText(getString(R.string.battery_level) + " " + level);
        mBatteryLevelProgress.setProgress(level);
    }
}

Update MainActivity class.
public class MainActivity extends Activity {

    private TextView mBatteryLevelText;
    private ProgressBar mBatteryLevelProgress;
    private BroadcastReceiver mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBatteryLevelText = (TextView) findViewById(R.id.textView);
        mBatteryLevelProgress = (ProgressBar) findViewById(R.id.progressBar);

        mReceiver = new BatteryBroadcastReceiver();
    }

    @Override
    protected void onStart() {
        registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        super.onStart();
    }

    @Override
    protected void onStop() {
        unregisterReceiver(mReceiver);
        super.onStop();
    }

    private class BatteryBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);

            mBatteryLevelText.setText(getString(R.string.battery_level) + " " + level);
            mBatteryLevelProgress.setProgress(level);
        }
    }
}


We also must unregister your receiver when activity is stop. Because as example if you close your application, but process will alive your application continue to receive some information.

Register our BroadcastReceiver in application

BatteryBroadcastReceiver mReceiver = new BatteryBroadcastReceiver();
registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

Run application.
We can change battery level of our emulator use console. We must connect to out AVD Emulator use console / terminal. If we run many emulator, each emulator will have unique port. Port number your emulator you can find in title of emulator window. As example port of my emulator is 5554.
Connect to emulator:
telnet localhost <PORT>

Change battery level of emulator:
power capacity <BATTERY_LEVEL_IN_PERCENT>

Change battery level to 50% use terminal
Next step is change battery level on emulator.
 Change battery level to 12% use terminal
As you can see TextView and ProgressBar were updated.

19 CommentsClose Comments

19 Comments

  • fengy
    Posted April 20, 2015 at 2:36 am 0Likes

    easy to understand

  • ht
    Posted April 20, 2015 at 8:25 am 0Likes
  • Vallny
    Posted April 20, 2015 at 12:49 pm 0Likes

    i think you can not unregister in onStop(),you should unregister in onDestory()

    • Posted April 20, 2015 at 1:40 pm 0Likes

      No, because when activity closed, not always calls onDestroy, as example if you press home button will execute just OnStop method

      • Vallny
        Posted April 20, 2015 at 1:51 pm 0Likes

        when you open the app by the shortcut again ,the receiver will not be registered,but when you press home button ,you will unregister again.
        perhaps register in the onStart() will be better

        • Posted April 20, 2015 at 5:09 pm 0Likes

          yes, it’s true. This is my mistake. I updated article and fix this problem. Thank you

  • Vincent
    Posted April 21, 2015 at 7:12 am 0Likes

    Hi, thank you for this article, small detail, I just wonder why have you redefined the “level” constant inside your inner class, instead of using the framework defined BatteryManager.EXTRA_LEVEL (which seems cleaner to me)?

    • Gnafu
      Posted April 21, 2015 at 12:02 pm 0Likes

      I was going to make the same comment, your example shows a minimum API of 7, which comply with the BatteryManager.EXTRA_LEVEL (introduced in API 5)

      This will go be beyond the purpose of this article, I suppose.

      Nice work

    • Posted April 21, 2015 at 8:46 pm 0Likes

      Hi Vincent, yes it’s a better way. Thank you. Code was updated.

  • Sergio
    Posted April 25, 2015 at 7:50 pm 0Likes

    Hi, I would suggest to register and unregister the receiver from within onResume and onPause methods. It prevents using resources when the activity is partially hidden. (i.e. by a dialog box).

    • Posted April 27, 2015 at 3:48 pm 0Likes

      Hi Sergio,

      thank you for this comment. Of course for this example better way use onResume and onPause, but for general is better place to register and unregister receiver are onStart and onStop

  • mohizur raheman
    Posted January 14, 2017 at 8:56 am 0Likes

    can we create an app to send battery status to microcontroller via usb

    • Posted January 21, 2017 at 9:14 am 0Likes

      You can send information from service as example.

  • Ricardo Angulo
    Posted August 16, 2017 at 5:28 pm 0Likes

    thank you for this article

Leave a comment