Android Broadcast Receiver – Battery Indicator example

In this post, we will learn about Broadcast receivers, an essential building block of Android system with a simple example.

What is Broadcast Receivers?

Broadcast Receivers is an Android implementation of system-wide publish/subscribe mechanism.

The receiver is simply a dormant code that gets activated once an event it is subscribed to happens.

The system itself broadcasts events all the time. For example, when an SMS arrives, or call comes in, or battery runs low, or system gets booted, all those events are broadcasted and any number of receivers could be triggered by them.

[pgsubscribe]

You can also send your own broadcasts from one part of your application to another, or a totally different application.

Broadcast receivers themselves do not have any visual representation nor are they actively running in memory. But when triggered, they get to execute some code, such as start an activity, a service, or something else what we defined.

What are we going to develop?

A simple application which displays the % of charge available in your devices’ battery. Progress bar will be used to display the % of battery.

Quick Links

Project Structure

  • Create new android project [File >> New >> Android Project] with project name BatteryIndicator
  • Click next and select target android device version [I chose version 2.2]
  • Click next and enter package name – ‘com.prgguru.android’
  • Click finish

Code Listings

Layout XML:

In the res/layout folder, we will create a simple layout for our application which has a text view to display the % of Battery in words and Progress bar to display the % of Battery graphically.

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >
<TextView
android:id="@+id/textfield"
 android:layout_marginTop="40dip"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="center"/>
<ProgressBar
android:id="@+id/progressbar"
 android:layout_width="wrap_content"
android:layout_height="wrap_content"
 android:layout_marginTop="20dip"
 android:layout_gravity="center"
 android:minWidth="200dip"
 android:minHeight="100dip"
 android:max="100"
 style="?android:attr/progressBarStyleHorizontal"/>
</LinearLayout>

As we are done with layout, let us turn towards application logic.

BatteryIndicatorActivity.java

package com.prgguru.android;

import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.ProgressBar;
import android.widget.TextView;

public class BatteryIndicatorActivity extends Activity {
        //Create Broadcast Receiver Object along with class definition
	private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
		@Override
          //When Event is published, onReceive method is called
		public void onReceive(Context c, Intent i) {
              //Get Battery %
			int level = i.getIntExtra("level", 0);
              //Find the progressbar creating in main.xml
			ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
              //Set progress level with battery % value
			pb.setProgress(level);
              //Find textview control created in main.xml
			TextView tv = (TextView) findViewById(R.id.textfield);
              //Set TextView with text
			tv.setText("Battery Level: " + Integer.toString(level) + "%");
		}

	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
           //Set layout we created
		setContentView(R.layout.main);
           //Register the receiver which triggers event
           //when battery charge is changed
		registerReceiver(mBatInfoReceiver, new IntentFilter(
				Intent.ACTION_BATTERY_CHANGED));
	}
}

[pglinkadssmall1]

Demo

Congratulations, We are done.
Let us test the application:
Right click on the project >> Run as >> Android application >> Choose emulator or device
You could see this screen:

Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.

[pglinkadssmall]

Reference:

Android Broadcase Receiver

I hope you enjoyed the post!! 🙂

Suggested posts for further reading


[pgfeedback]
[pgwriteforus]

Related Articles

Author: Udhay

Share This Post On
468 ad
  • Arithmetic

    I’m getting an error, in the .java, “main cannot be resolved or is not a field”. It’s line 37 where it says,

    setContentView(R.layout.main)

    Can you help me?

    • Arithmetic

      Never mind, I had renamed the res/layout/main.xml to activity_battery_indicator, that’s why it could find main.

  • harish

    pls get me the code to check the battery level in background as service and do some action if its low…. thanks in advance

  • manasakotturi

    Thank you

  • Monish

    Thnks its really gud but i tried on lover version its give a error

  • icy

    thanx!! it was an gud example.. can i get some more examples regarding broadcast receiver?? for screen on and screen offf….

  • Gunajn

    good work…………..

  • malleswari

    plz give brief discussion about broad cast receiver for mobile security purpose

  • Vishal

    how will i show that battery image insteat of horizontal progress bar…?its urgent reply fast..!

  • saravana

    this is very useful to me, i need some more information about android, im in begginer to learn these concept, can you help me…

  • Wolfgang

    ok, sorry…found the error…:) wrong property in android manifest

  • Mayaa

    Really helpful post!! Thanks. Even this website http://www.compiletimeerror.com/2013/03/android-broadcast-receiver-in-detail.html also addresses something similar.. Have a look.. Might help..

  • Adarsh

    Thanks for this great article about Broadcast Receiver… simple and understandable..

  • dangwru

    thank for post

  • stanks

    hm why ‘Create new android project [File >> New >> Android Project] with project name TexttoSpeech’ if we are creating battery progress bar?

    • Thanks for letting us know. Project name has been updated.

  • Solomon89

    Thanks!

  • Debayan Das

    very good example, thanks

  • luisk

    Can you help me with the idea making a broadcast for a change in the database

    • Am writing an article on syncing MySQL DB with local SQLite which may help you. Keep watching the space for update on it.

      • luisk

        Thanks!

  • ranjithstar256

    very helpful example! helped me to know what is broadcast receiver and its dynamic implementation without declaring receiver to the manifest file! Thank You!

  • Thanks Ranjith,

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares