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