Android battery status use BroadcastReceiver


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.

CategoriesUncategorized

19 thoughts on “Android battery status use BroadcastReceiver

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

      1. 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

  1. 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)?

    1. 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

  2. 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).

    1. 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

Leave a Reply

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