Android App Component

Android battery status use BroadcastReceiver

Alex Zhukovich 3 min read
Android battery status use BroadcastReceiver
Table of Contents

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.

Demo of battery percentage Android app

Creating a project

For this project we will use Android studio and the first step is create a project.

Step 1: Project name and package

Creating a project: Step 1

Step 2: Targer Android device configuration

Creating a project: Step 2

Step 3: Template

Creating a project: Step 3

Step 4: Activity configuration

Creating a project: Step 4

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));

Running 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>.
Changed battery level to 50% via terminal

Next step is change battery level on emulator.

Changed battery level to 12% via terminal

As you can see TextView and ProgressBar were updated.


Mobile development with Alex

A blog about Android development & testing, Best Practices, Tips and Tricks

Share
More from Mobile development with Alex

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Mobile development with Alex.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.